简体   繁体   English

正则表达式匹配模式或匹配所有其他内容-匹配优先级问题?

[英]Regex to match pattern or match everything else - match precendence issue?

I'm trying to write a regex that will use something like this 我试图写一个正则表达式,将使用这样的东西

/([;\.])|([\s\S]+)/gi

to split this 拆分这个

a.b.cad0i2!--as.d;e;f;g00))(

into this 进入这个

['a','.','b','.','cad0i2!--as','.','d',';','e',';','f',';','g00))(']

ie. 即。 Everything in the original string is in the final array, with the input regex simply listing a complex set of potential delimiters and I don't want to repeat the list of delimiters in the regex. 原始字符串中的所有内容都位于最终数组中,输入正则表达式只是列出了一组复杂的潜在定界符,我不想重复正则表达式中的定界符列表。

Is this possible? 这可能吗?

Use string.match function. 使用string.match函数。

> "a.b.cad0i2!--as.d;e;f;g00))(".match(/[^;.]+|[;.]/g)
[ 'a',
  '.',
  'b',
  '.',
  'cad0i2!--as',
  '.',
  'd',
  ';',
  'e',
  ';',
  'f',
  ';',
  'g00))(' ]

[^;.]+ matches any character but not of ; [^;.]+匹配任何字符,但不匹配; or . . one or more times. 一次或多次。

| OR, 要么,

[;.] match ; [;.]比赛; or . .

Try this code: 试试这个代码:

 var re = /(?=([.;])(?=[^.;]+))/gi; var str = 'abcad0i2!--as.d;e;f;g00))('; var res = []; var result = str.split(re); for (var letter of result) { res.push(letter.replace(/^[.;](?=.+)/, '')); } alert(res); 

Result: 结果:

a,.,b,.,cad0i2!--as,.,d,;,e,;,f,;,g00))(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM