2012-03-05 121 views
2

我想爲下面的字符串使用正則表達式。示例字符串的正則表達式字符串

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

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

我想出了下面的正則表達式來捕捉「文本」和「計數」,但它不符合上述第2前。

@"(?<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); 
} 

回答

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); 
    } 
} 
+0

不起作用。 。+將爲所有第一名前鋒奪冠。 – hIpPy 2012-03-05 23:15:58

+0

@hIpPy:現在修復。 – Ryan 2012-03-05 23:23:35

+0

minitech,仍然不起作用。 – hIpPy 2012-03-05 23:31:54

1

試試這個

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

更新

實在是太多的方法給你提供的信息去這裏。
這可能是完全靈活的版本。

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

不適用於2nd。 – hIpPy 2012-03-05 23:23:00

0

正則表達式的解決方案:

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