正则表达式如何匹配带有可选周围括号的模式? [重复]

时间:2022-09-13 11:41:54

This question already has an answer here:

这个问题在这里已有答案:

I'm looking for a single line regular expression which matches a pattern with optional parentheses. When the parentheses are present they should not be included in the matched pattern.

我正在寻找一个单行正则表达式,它匹配带有可选括号的模式。当括号出现时,它们不应包含在匹配的模式中。

The following bold text demonstrates what should / shouldn't match:

以下粗体文本演示了应该/不应该匹配的内容:

Should Match:

应匹配:

"Title Description (AAA123)"

“标题说明(AAA123)”

"(ABC000) Title Description"

“(ABC000)标题说明”

"Title Description DEF999"

“标题说明DEF999”

"Title - RST321 - Description"

“标题 - RST321 - 说明”

Shouldn't Match:

不应该匹配:

"Title Description AB123"

“标题说明AB123”

"Title Description CCC456a"

“标题说明CCC456a”

"Title Description (ABE999c)"

“标题说明(ABE999c)”

1 个解决方案

#1


3  

Try this regex:

试试这个正则表达式:

\b[a-zA-Z]{3}\d{3}\b

This matches:

匹配:

# \b          - A word boundary,
# [a-zA-Z]{3} - followed by 3 letters,
# \d{3}       - followed by 3 digits,
# \b          - followed by a word boundary.

The regex doesn't care about parentheses, like requested, but doesn't match strings that are too long.

正则表达式不关心括号,如请求,但不匹配太长的字符串。

#1


3  

Try this regex:

试试这个正则表达式:

\b[a-zA-Z]{3}\d{3}\b

This matches:

匹配:

# \b          - A word boundary,
# [a-zA-Z]{3} - followed by 3 letters,
# \d{3}       - followed by 3 digits,
# \b          - followed by a word boundary.

The regex doesn't care about parentheses, like requested, but doesn't match strings that are too long.

正则表达式不关心括号,如请求,但不匹配太长的字符串。