hIpPy
hIpPy

Reputation: 5105

Regex string for sample strings

I want a regex for below strings.

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

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

I came up with the following regex to capture 'text' and 'count' but it does not match the 2nd ex above.

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

Upvotes: 2

Views: 638

Answers (3)

Ry-
Ry-

Reputation: 225014

Just make the group optional:

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

Upvotes: 2

Jack
Jack

Reputation: 16724

Regexp solution:

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() solution:

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

Output:

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

Upvotes: 0

user557597
user557597

Reputation:

Try this

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

update

There is really too many ways to go here given the information you provide.
This could be the totally flexible version.

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

Upvotes: 1

Related Questions