1

Let me explain the actual problem I am facing.

When my SearchString is C+, the setup of regular expression below works fine. However when my searchstring is C++, it throws me an error stating --

  parsing "C++" - Nested quantifier +.

Can anyone let me know how to get past this error?

RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
1
  • Well, you did not post the regex yet :) Commented Jul 21, 2013 at 15:10

3 Answers 3

3

First of all, I believe that you'll learn much more by looking at some regex tutorials instead of asking here at your current stage.

To answer your question, I would like to point out that + is a quantifier in regexp, and means 1 or more times the previous character (or group), so that C+ will match at least 1 C, meaning C will match, CC will match, CCC will match and so on. Your search with C+ is actually matching only C!

C++ in a regex will give you an error, at least in C#. You won't with other regex flavours, including JGsoft, Java and PCRE (++ is a possessive quantifier in those flavours).

So, what to do? You need to escape the + character so that your search will look for the literal + character. One easy way is to add a backslash before the +: \+. Another way is to put the + in square brackets.

This said, you can use:

C\+\+

Or...

C[+][+]

To look for C++. Now, since you have twice the same character, you can use {n} (where n is the number of occurrences) to denote the number of occurrences of the last character, whence:

C\+{2}

Or...

C[+]{2}

Which should give the same results.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jerry for the detail explanation. This helped to resolve my issue.
3

Plus + is a special symbol in regular expression. You must escape it.

Regex regex = new Regex(@"C+\+");

2 Comments

Thanks for your response @Ghost. However can you let me know how to get past this error? How does it allow C+ to go through and not C++?
@user2604371 C+ means one or more C character (as in CCCC).
1

I could not help but notice @ghost's answer is wrong.

This snippet is wrong:

Regex regex = new Regex(@"C+\+");

Because the first + is not escaped. So the meaning still is "one or more C characters followed by a plus sign". The correct form would be @"C\+\+"

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.