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 for matching a string with possible spaces at beginning and end of string with a hyphen in the middle

I’m trying to put together a js flavor of regex to match a string like in the following examples where there may be a whitespace at the front or back of the string, or both front and back. But not within the string

Examples:

'Z5LW-KRT2'       MATCH
' Z5LW-krt2'      MATCH
'Z5LW-KRT2 '      MATCH
' Z5LW-KRT2 '     MATCH

' Z5LW-K RT2 '    NO MATCH

So far i have come up with the below which matches if there is no whitespace anywhere, but i cant figure out how to include white space at the beginning or end but not within like in the examples

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

^[A-Za-z0-9\-]+$

>Solution :

You should add \s* to match spaces so the result regex should look like ^\s*[A-Za-z0-9\-]+\s*$ and even you can reduce it to ^\s*[\w\-]+\s*$ if you want to use the build-in class \w.

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