括号中的正则表达式开头 [英] regex in parenthesis at the beginning

查看:353
本文介绍了括号中的正则表达式开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式试图按专业划分问题.说我有以下正则表达式:

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)

(7)以下哪一项被认为是食道癌的危险因素?

(7)Which of the following is LEAST to be considered as a risk factor for esophageal cancer?;

为此(正确匹配:8和13)

And for this (correct match: 8 and 13)

(8,13)30岁女性闭经,血清雌激素水平低和血清LH/FSH高,最可能的诊断是:

(8,13)30 year old woman with amenorrhea, low serum estrogen and high serum LH/FSH, the most likely diagnosis is:

但不适用于此错误匹配(错误匹配:20个).

But not for this one (incorrect match: 20).

早孕自然流产(20周之前)最常见的原因是:

First trimester spontaneous abortion (before 20 wk) is most commonly due to:

在问题的开头,我只需要括号中的数字,其他所有括号都应忽略.仅使用正则表达式就可以做到这一点(超前吗?).

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 重置匹配开始,尝试:

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
)

在eval.in进行测试

这篇关于括号中的正则表达式开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆