[英]match regular expression using regex order, not string order in JavaScript
我正在寻找从字符串中提取特定模式,如果不存在,则提取另一个模式。
有问题的字符串可能以任何顺序具有两种模式。 无论顺序如何,我都希望第一个模式优先。
我知道我可以通过多行/ match
调用来做到这一点,但我想知道是否可以通过单个match
调用来做到这一点。
var s1 = "hello A123 B456"
var s2 = "hello B123 A456"
我想先捕获A###
模式,并且只有当它不存在时,才捕获B###
模式
console.log(s1.match(/((A|B)\d{3})/)[1]); // A123
console.log(s2.match(/((A|B)\d{3})/)[1]); // B123 -- but I want it to capture the A123 first
我想您可以通过将首选选项锚定到主题的开头来实现这一点:
re = /^.*?(A\\d+)|(B\\d+)/ test = [ "hello A456 B123", "hello B123 A456", "hello A456 zzz", "hello B123 zzz", ]; for (t of test) { m = t.match(re) console.log(t, '=', m[1] || m[2]) }
一个缺点是您有两个组可供选择。
您可以使用以下任一正则表达式模式来完成此操作:
^(?:.*(A\d{3})|.*(B\d{3})) # pattern 1
^(?:.*(?=A)|.*(?=B))([AB]\d{3}) # pattern 2
优点/缺点:简单,但使用两个捕获组
^(?:.*(A\d{3})|.*(B\d{3}))
这是如何工作的:
^
将其锚定到字符串的开头(?:.*(A\\d{3})|.*(B\\d{3}))
匹配以下任一选项
.*
匹配任何字符(换行符除外)任意次数(它是贪婪的,所以它会尽可能多地匹配)(A\\d{3})
匹配A
后跟 3 位数字第二个选项与第一个选项相同,但这适用于回溯:
^(?:.*(A\d{3})|.*(B\d{3}))
hello B123 A456
^ # anchor to the start of the string (to the location before the h)
# now attempt option 1 of the alternation: .*(A\d{3})
.* # match any character any number of times (greedy)
hello B123 A456 # this is what we currently match
# now backtrack to find A\d{3}
hello B123 A # we found A, check to see if \d{3} matches
hello B123 A456 # pattern fulfilled; result you're looking for in group 1
s = ["hello A123 B456","hello B123 A456", "hello B123"] r = /^(?:.*(A\\d{3})|.*(B\\d{3}))/ for (x of s) { m = x.match(r) if (m) console.log(m[1] || m[2]) }
优点/缺点:不太容易理解,但只使用一个捕获组
^(?:.*(?=A)|.*(?=B))([AB]\d{3})
这是如何工作的:
^
将其锚定到字符串的开头(?:.*(?=A)|.*(?=B))
匹配以下任一选项
.*
匹配任何字符(换行符除外)任意次数(它是贪婪的,所以它会尽可能多地匹配)(?=A)
确保A
跟随当前位置(?=B)
代替([AB]\\d{3})
匹配A
或B
后跟 3 位数字 s = ["hello A123 B456","hello B123 A456", "hello B123"] r = /^(?:.*(?=A)|.*(?=B))([AB]\\d{3})/ for (x of s) { m = x.match(r) if (m) console.log(m[1]) }
您还可以通过负前瞻来实现结果。
var s1 = "hello A123 B456"; var s2 = "hello B123 A456"; const regex = /A\\d{3}|B\\d{3}(?!.*A\\d{3})/ console.log(s1.match(regex)[0]); console.log(s2.match(regex)[0]);
上面的正则表达式是说, A
有 3 位数字或B
有 3 位数字,如果后面没有跟有 3 位数字的A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.