什么正则表达式匹配单词与关键字'('?

时间:2013-12-11 13:38:42

标签: c# regex

在我的c#代码中,如果匹配特定单词之前的单词,我需要说一句话:

var match= Regex.Match(someLine, @"^(FIRST WORDS) (\w+) (SECOND WORDS | PROBLEM KEYWORD \() (\w+)", RegexOptions.IgnoreCase);

var neededWord= match.Groups[4].Value;

如果字符串等于“首字母问题关键字(再次出现)”,我想把'SOMETHING'作为我需要的词。但这不起作用。它返回一个空字符串。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

RegEx Demo

^FIRST WORDS[^\(]+\(([^\)]+)\)

Regular expression visualization

Debuggex Demo

<强>描述

^ assert position at start of the string
FIRST WORDS matches the characters FIRST WORDS literally (case sensitive)
[^\(]+ match a single character not present in the list below
    Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    \( matches the character ( literally
\( matches the character ( literally
1st Capturing group ([^\)]+)
    [^\)]+ match a single character not present in the list below
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    \) matches the character ) literally
\) matches the character ) literally

注意:如果您只需要单词SOMETHING我可以编辑RegEx,Group 1也会包含您要求的结果。