2

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

3 Answers 3

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@hIpPy: Really fixed now, and here's proof. Maybe next time don't say your code already works for the first test case if it doesn't ;)
minitech, it works. :) thanks. my regex works for 1st and not for 2nd.
1

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* \)
)?

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.