user1178492
user1178492

Reputation: 51

Regex Match Pattern in c#

Hey I have the following strings as input:

"abcol"  
"ab_col"  
"cold"  
"col_ab"  
"col.ab"  

I have the string col to search from. I'm using regex to match

Match matchResults = Regex.Match(input , "col", RegexOptions.IgnoreCase);

I want to match only the string that has this pattern [Any special character or nothing ] + col + [Any special character or nothing]

From the above inputs, I want to return only ab_col, col_ab , col.ab

Any help is highly appreciated.
Thanks

[Any special character] = [^A-Za-z0-9]

Upvotes: 1

Views: 6701

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213411

You can use this regex: -

(?:^.*[^a-zA-Z0-9]|^)col(?:[^a-zA-Z0-9].*$|$)

Explanation : -

(?:   // non-capturing
  ^   // match at start of the string
  .*[^a-zA-Z0-9]  // match anything followed by a non-alphanumeric before `col`
    |     // or
  ^       // match the start itself (means nothing before col)
)
  col  // match col
(?:   // non-capturing
  [^a-zA-Z0-9].*  // match a non-alphanumeric after `col` followed by anything
   $     // match end of string
   |     // or
   $     // just match the end itself (nothing after col)
)

Upvotes: 5

shift66
shift66

Reputation: 11958

@"(^|.*[\W_])col([\W_].*|$)" this is your pattern. \w is alphanumeric character and \W is non alphanumeric character. ^ means line start and $ means line end. | is the or. so (^|.*\W) means line start or some characters and non alphanumeric after them.

EDIT:

yes, underline is alphanumeric too... so you should write [\W_] (non alphanumeric or underline) instead of \W

Upvotes: 2

Related Questions