使用正则表达式分析字符串,并将结果存储在数组或字符串中

Parse strings with a regex and store the result in an array or a string

本文关键字:字符串 存储 结果 数组 正则表达式      更新时间:2023-09-26

我需要一些帮助来改进我的代码:

我是regex系统的初学者。

我想在脚本中完成下面的NUMBER,并将其存储在字符串或数组中,以便于输出"NUMBER1,NUMBER1_NUMBER2_,NUMBER2"。我不明白为什么,我想在末尾使用jsut NUMBER;

function fetchnumber(){
    extract = "";
    for(picture = 1 ; picture < 5; picture++){
 // get background image as a string as this :
 // url('http://www.mywebsite.com/directory/image_NUMBER_.png');
       var NumberOfPicture = document.getElementById(picture).style.backgroundImage ;

       reg = /'_(.*)'_/;
         extract += reg.exec(NumberOfPicture);

       }
     } 

我为您编写了这个小示例。希望这对你有所帮助。

var inputString = 'http://www.mywebsite.com/directory/image_123_.png';
var imageNumber = (/image_([^_]+)_'.'w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
   // here you can do something with finded 
   // part of text. 
}

我祝你在执行方面好运。

你问为什么有[1]而不是[0]。解释是我们需要正则表达式不匹配时的行为相同。这是MDN 的报价

exec()方法在指定字符串中执行匹配项的搜索。返回结果数组或null。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

所以。如果正则表达式匹配,则返回的数组将包含从位于零索引([0])处的匹配字符串开始,并且第一个后引用位于第一个索引[1]处,后引用是方括号(sddsd)之间的符号。但如果没有匹配,我们将通过[,false]作为输出,因此我们将期待结果转换为第一个数组索引[1]。尝试使用不同输入的代码。例如:

var inputString = 'some text some text ';
var imageNumber = (/image_([^_]+)_'.'w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
   // here you can do something with finded 
   // part of text. 
}

所以。。在这种情况下,根本不会执行该条件。我的意思是:

if (imageNumber) {
   // here you can do something with finded 
   // part of text. 
}