How to math string containing '+,()' in .net

  • Thread starter Thread starter archana
  • Start date Start date
A

archana

Hi all,

I want to apply regular expresion on string containing chatacters like
'(,')',+' and many such which we are using while creating pattern for
regulat expression.

But when i am applying regular expression on input string containing
abov character exception is getting raised.

Can some one tell me why this is happening and how to overcome this
problem.

Please help me.

thanks in advance.
 
In order to represent normal characters, all of the following must be
escaped by a leading "\", e.g. the *character* "+" is "\+" in RegEx lingo;
otherwise, they represent the RegEx token, so "+" means "One or more
matches", etc

.. ? / \ [ ] { } ( ) + * |

Marc
 
archana said:
Hi all,

I want to apply regular expresion on string containing chatacters like
'(,')',+'

these are characters which have special meaning in regular expresions.
use \ before: \( \) \+
 
Oh - and for that reason it is often very convenient to use @"somestring"
notation in C# - so you can say:

new Regex(@"a\+b"); // means match the string "a+b"

which thanks to C# string-escaping is identical to:

new Regex("a\\+b");

The second one could be mis-read by somebody in a hurry as:

match a followed by one or more slashes followed by a b, e.g. the strings
@"a\b", @"a\\\b" etc

Regardles of whether you prefer using the C# @"" or "" syntax for RegEx, I
recommend you choose one and stick to it religiously for all RegEx in any
project; alternatively (better), put the patterns into a separate resource
file so that when editing them you only need to think about RegEx escaping,
and not C# escaping as well.

Marc
 
Hi,
thanks for your reply.

can you tell me one more thing?

What is difference in using () and [] in pattern.
Means what if i specify (ab) and [ab]. what is matching criteria then?

Thanks.
 
[ab] means "match a or b"
(ab) meeans "match the string ab, as a block usable for replace", e.g.

(note that pretty-much any valid regex expression can be used as a block
between the round brackets)

Debug.WriteLine(new Regex("(a)(bc)(d)").Replace("tahshabcdasd", "$1QQQ$3"));

will output "tahshaQQQdasd", because we have replaced the found expression
with the values of the first block ("a"), a literal "QQQ", and the third
block ("d")

Does that make sense?

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top