简体   繁体   English

RegExp 捕获不匹配

[英]RegExp capturing non-match

I have a regex for a game that should match strings in the form of go [anything] or [cardinal direction] , and capture either the [anything] or the [cardinal direction] .我有一个游戏的正则表达式,它应该以go [anything][cardinal direction]的形式匹配字符串,并捕获[anything][cardinal direction] For example, the following would match:例如,以下将匹配:

go north go foo north go north go foo north

And the following would not match:以下不匹配:

foo go foo go

I was able to do this using two separate regexes: /^(?:go (.+))$/ to match the first case, and /^(north|east|south|west)$/ to match the second case.我能够使用两个单独的正则表达式来做到这一点: /^(?:go (.+))$/匹配第一种情况,和/^(north|east|south|west)$/匹配第二种情况。 I tried to combine the regexes to be /^(?:go (.+))|(north|east|south|west)$/ .我试图将正则表达式组合为/^(?:go (.+))|(north|east|south|west)$/ The regex matches all of my test cases correctly, but it doesn't correctly capture for the second case.正则表达式正确匹配我的所有测试用例,但它没有正确捕获第二种情况。 I tried plugging the regex into RegExr and noticed that even though the first case wasn't being matched against, it was still being captured.我尝试将正则表达式插入 RegExr 并注意到即使第一个案例没有匹配,它仍然被捕获。

How can I correct this?我该如何纠正?

Try using the positive lookbehind feature to find the word "go".尝试使用正向后视功能来查找单词“go”。

(north|east|south|west|(?<=go ).+)$

Note that this solution prevents you from including ^ at the start of the regex, because the text "go" is not actually included in the group.请注意,此解决方案会阻止您在正则表达式的开头包含^ ,因为文本“go”实际上并未包含在该组中。

You have to move the closing parenthesis to the end of the pattern to have both patterns between anchors, or else you would allow a match before one of the cardinal directions and it would still capture the cardinal direction at the end of the string.您必须将右括号移到模式的末尾才能在锚点之间拥有两个模式,否则您将允许在主要方向之一之前进行匹配,并且它仍然会在字符串的末尾捕获主要方向。

Then in the JavaScript you can check for the group 1 or group 2 value.然后在 JavaScript 中,您可以检查组 1 或组 2 的值。

^(?:go (.+)|(north|east|south|west))$
                                   ^  

Regex demo正则表达式演示

Using a lookbehind assertion ( if supported ), you might also get a match only instead of capture groups.使用后视断言(如果支持),您也可能只获得匹配而不是捕获组。

In that case, you can match the rest of the line, asserting go to the left at the start of the string, or match only 1 of the cardinal directions:在这种情况下,你可以匹配行的其余部分,主张go在字符串的开始向左,或只匹配基本方向的1:

(?<=^go ).+|^(?:north|east|south|west)$

Regex demo正则表达式演示

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

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