问题描述
我有一个正则表达式试图按专业划分问题.说我有以下正则表达式:
I have a regex trying to divide questions by speciality. Say I have the following regex:
(?P<speciality>[0-9x]+)
此问题很好用(正确匹配:7)
It works fine for this question (correct match: 7)
为此(正确匹配:8和13)
And for this (correct match: 8 and 13)
但不适用于此错误匹配(错误匹配:20个).
But not for this one (incorrect match: 20).
在问题的开头,我只需要括号中的数字,其他所有括号都应忽略.仅使用正则表达式就可以做到这一点(超前吗?).
I only need the numbers in parentheses at the beginning of the question, all other parentheses should be ignored. Is this possible with a regex alone (lookahead?).
推荐答案
如果您的正则表达式支持\G
连续匹配和\K
重置匹配开始,尝试:
If your regex flavor supports \G
continuous matching and \K
reset beginning of match, try:
(?:^\(|\G,)\K[\dx]+
^\(
将在开始|
处匹配括号,或者\G
在最后一个匹配项之后匹配,
.然后\K
重置并匹配+
一个或多个[\dx]
. (\d
是[0-9]
的速记).匹配项将在$0
中.
^\(
would match parenthesis at start |
OR \G
match ,
after last match. Then \K
resets and match +
one or more of [\dx]
. (\d
is a shorthand for [0-9]
). Matches will be in $0
.
在regex101.com上进行测试; 正则表达式常见问题解答
PHP示例
$str = "(1x,2,3x) abc (1,2x,3) d";
preg_match_all('~(?:^\(|\G,)\K[\dx]+~', $str, $out);
print_r($ out [0]);
Array
(
[0] => 1x
[1] => 2
[2] => 3x
)
这篇关于括号中的正则表达式开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!