Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用正则表达式匹配分割文本_Javascript_Regex - Fatal编程技术网

Javascript 如何使用正则表达式匹配分割文本

Javascript 如何使用正则表达式匹配分割文本,javascript,regex,Javascript,Regex,从这种文本出发 var txt = "hello [a14] world, and [b74] some more [h85], ..." 我期待结果 var arr = [ "hello " , "[a14]" , " world, and " , "[b74]" , " some more " , "[h85]" , &q

从这种文本出发

var txt = "hello [a14] world, and [b74] some more [h85], ..."
我期待结果

var arr = 
  [ "hello "
  , "[a14]"
  , " world, and "
  , "[b74]"
  , " some more "
  , "[h85]"
  , ", ..."
  ] 
到目前为止我已经试过了,但是掌握正则表达式对我来说仍然很困难

let txt=“你好[a14]世界,还有[b74]更多[h85],”
让arr=txt.match(/(\[(.*)\])|(.*)/g)
控制台日志(arr)
。作为控制台包装{最大高度:100%!重要;顶部:0;}
您可以尝试
/(\[^\]\[]*\].[^\]\[]+/g
。区别在于:

  • 使用
    +
    而不是
    *
    至少获取一个字符并避免匹配空字符串
  • [^\]\[]
    为您提供了“非括号的任何字符”,因此您可以避免与
    进行非贪婪匹配
  • 将捕获组转移到更直观的位置
const txt=“你好[a14]世界,还有[b74]更多[h85],…”;
console.log(txt.match(/(\[^\]\[]*\].[^\]\[]+)/g))

。作为控制台包装{max height:100%!important;top:0;}
您还可以尝试在lookarounds上拆分:

var text=“你好[a14]世界,还有[b74]更多[h85],…”;
var arr=text.split(/(?=\[)|)(?您可以使用
.split()
。诀窍是捕获拆分条件,它将显示在结果数组中:

let txt=“你好[a14]世界,还有[b74]更多[h85],”
让正则表达式=/(\[^\]]*\]/;
让结果=txt.split(regex);

console.log(result);
我选择这个,因为这个解决方案总是返回一个数组,即使字符串是空的,当文本以
[cod]
开头或结尾时,也不会在开头或结尾给出空字符串,可以使用
/*(\[^\]*\])*/