样本字符串的正则表达式字符串

时间:2012-03-05 23:10:36

标签: c# regex

我想在下面的字符串中使用正则表达式。

string: Some () Text (1)
I want to capture 'Some () Text' and '1'

string: Any () Text
I want to capture 'Any () Text' and '0'

我想出了以下正则表达式来捕捉'text'和'count',但它与上面的第二个ex不匹配。

@"(?<text>.+)\((?<count>\d+)\)

c#:

string pattern = @"(?<text>.+)\((?<count>\d+)\)";
Match m = Regex.Match(line, pattern);
count = 0;
text = "";
if (m.Success)
{
    text = m.Groups["text"].Value.Trim();
    int.TryParse(m.Groups["count"].Value, out count);
}

3 个答案:

答案 0 :(得分:2)

只需将该组设为可选:

string pattern = @"^(?<text>.+?)(\((?<count>\d+)\))?$";
Match m = Regex.Match(line, pattern);
count = 0;
text = "";
if (m.Success)
{
    text = m.Groups["text"].Value.Trim();

    if(m.Groups["count"].Success) {
        int.TryParse(m.Groups["count"].Value, out count);
    }
}

答案 1 :(得分:1)

试试这个

(?<group_text>Some Text) (?:\((?<group_count>\d+)\)|(?<group_count>))

<强>更新

根据您提供的信息,有太多方法可以到这里 这可能是完全灵活的版本。

(?<group_text>
   (?:
       (?! \s* \( \s* \d+ \s* \) )
       [\s\S]
   )*
)
\s*
(?:
    \( \s* (?<group_count>\d+ ) \s* \)
)?

答案 2 :(得分:0)

Regexp解决方案:

var s = "Some Text (1)";
var match = System.Text.RegularExpressions.Regex.Match(s, @"(?<text>[^(]+)\((?<d>[^)]+)\)");
var matches = match.Groups; 
if(matches["text"].Success && matches["d"].Success) {
    int n = int.Parse(matches["d"].Value);
    Console.WriteLine("text = {0}, number = {1}", match.Groups["text"].Value, n);
} else {
    Console.WriteLine("NOT FOUND");
}

.Split()解决方案:

var parts = s.Split(new char[] { '(', ')'});
var text = parts[0];
var number = parts[1];
int n; 
if(parts.Length >= 3 int.TryParse(number, out n)) {
    Console.WriteLine("text = {0}, number = {1}", text,n);
} else {
    Console.WriteLine("NOT FOUND");
}

输出:

text = Some Text , number = 1
text = Some Text , number = 1