Monjurul Habib Monjurul Habib - 2 months ago 11
C# Question

C# Regular expression for skiping words that starts with some characters

I want to find and replace some words from a string. But I want to skip words containing special characters like '

@,#,?,!
' etc. I have written one but the problem is it selects first bracket also.

Example:
(Victoria Basement OR QVB @Victoria Basement #Victoria Basement ?#Victoria Basement!?)


Regex:
[^#@?!%$&]Victoria Basement


Expected output: it should select only "
Victoria Basement
" not "
(Victoria Basement
" or "
@Victoria Basement #Victoria Basement ?#Victoria Basement!?
"

Please help.

Answer

Please try this: ((?<![#@\?!%$&])Victoria Basement)

See it working here: https://regex101.com/r/tV1rV5/1

[EDIT] add explanation:

So [^#@?!%$&]Victoria Basement will capture 1 character for [^#@?!%$&] but in case of (Victoria Basement it won't be matching so you need to do a "negative look behind" to exclude that character from the match like (?<![#@\?!%$&]) then you wrap everything with () if you want to capture! ;)

Comments