tags:

views:

94

answers:

3

Hello there,

I am somewhat confused right now with a obviously pretty simple regex but it must be the lack of caffein or the weather today. Basically what I have is a string that can be something like 'sw' or 'ee' or 'n.a.'.

Now what I want & need is a regex.match that gives me back '' in case the provided string is 'n.a.', in all other cases I want '_' (underscore + the original value). Is that possible?

A: 

The following regex will only mstch your non 'n.a' string values.

^(?!n\.a).*
Stevo3000
A: 

You can use a call to Regex.Replace and use the match evaluator delegate. Basically:

return Regex.replace( "sw|ee|n\.a\.", match => match.Value == "n.a." ? String.Empty : String.Format("_{0}", match.value) );

Adam Luter
You may want to use "^(?:sw|ee|n\.a\.)$" as the match, if you only have that in the data.
Adam Luter
But I agree with everyone else, use a switch statement.
Adam Luter
A: 

Your question could be a bit clearer, but essentially the regex

(n.a.)|([a-z]+)

sets up two groups - the first matching 'n.a.' and the second matching anything with one or more lowercase characters. So, you can match against this regex and see if the first or the second group are non-empty - and prepend the '_' if the second group gets a hit.

Vinay Sajip