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 – space or character at the start or end of string

Imagine you have the word Test and you want the regex to match only if certain characters are at the begininng or the end of the match.

Example: Lets say you want the one or more of the following (Including space) characters (),&=<> to be allowed at the beginning and end of the sentence and you have the following test cases:

Test[MATCH]
 Test [MATCH]
This is a Test sentence [MATCH]
This >Test is a sentence [MATCH]
This Test) is a sentence [MATCH]
This Test&Hello is a sentence [MATCH]
This is a _Test sentence [NO MATCH]
This sentence is ?Test [NO MATCH]

Is it possible please?

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

>Solution :

I think, something like this should work:

(?<![^\(\)\,\&\=\<\>\s])Test(?![^\(\)\,\&\=\<\>\s])

[^\(\)\,\&\=\<\>\s] represents a character class matching any character except for (),&=<> and whitespaces

([ab] matches either a or b, thus [^ab] matches anything except for a and b)

(?<!) is negative lookbehind
(?!) is negative lookahead

enter image description here

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