Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex: Exact match ignoring leading and trailing whitespaces

for selecting amongst couple of others, I need to match an exact string which is surrounded by leading and trailing whitespaces and linebreaks in RegEx and I cannot get it to work, it drives me crazy.

Example text (the dots are whitespaces):

..
............SCV
..........

I need to check if this text is equal ‘CV’ (and it should NOT match ‘SCV’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to figure out using non-capturing groups (?:\s*) like here: https://regex101.com/r/n3L0Vu/1

but either it matches whitespaces too, or it also matches SCV when I just want it to match CV.

Thank you very much for help, I very appreciate it.

Edit: Oh, in above example I justed used one word, but it should also work for sentences containing whitespaces between the words like "This is my CV"

>Solution :

Try with the following regex:

^\W*(<your_matching_string>)\W*$

It will enclose your match between

  • ^\W*: start of string and any character other than alphanumeric ones (optional)
  • \W*$: any character other than alphanumeric ones (optional) and end of string

Note: You can remove the parentheses, here are just used for clarity reasons.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading