bAN
bAN

Reputation: 13825

Pattern not surrounded by numbers or alphanumerics

I would like to find some words not surrounded by any numerics or alphanumerics or surrounded by nothing. So if I'm looking for Foo123 I would like this result

="Foo123"; =>TRUE
barFoo123; =>FALSE
Foo123 =>TRUE
BarBar123Foo123Bar; =>FALSE
;Foo123 =>TRUE

I just built this expression:

(^[^0-9a-zA-Z]?)WORDTOFIND([^0-9a-zA-Z]?$)

I was pretty sure I'm in the right way but when I'm using it like this:

if (Regex.IsMatch(line, string.Format(@"(^[^0-9a-zA-Z]?){0}([^0-9a-zA-Z]?$)",snCode)) )
{   
}

It doesn't work. What am I doing wrong?

Upvotes: 0

Views: 131

Answers (2)

Joey
Joey

Reputation: 354386

You're essentially looking for

 (?<![a-zA-Z0-9])Foo123(?![a-zA-Z0-9])

This uses a lookahead and lookbehind to make sure that there isn't an alphanumeric character either before or after Foo123. This assumes ASCII, though.

Upvotes: 3

tilish
tilish

Reputation: 1113

The following matches the strings you do NOT want so do !Regex.IsMatch()

(^([0-9a-zA-Z])+{0}.*)|(.*{0}([0-9a-zA-Z])+)

Upvotes: 0

Related Questions