Reputation: 79
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);
Upvotes: 1
Views: 1991
Reputation: 37908
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\+\+"
Upvotes: 1
Reputation: 6082
Plus +
is a special symbol in regular expression. You must escape it.
Regex regex = new Regex(@"C+\+");
Upvotes: 3
Reputation: 71598
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.
Upvotes: 3