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 that doesn't end with a specific character compilation issue

I have to make a regex that covers this conditions:
The word can start with non mandatory _
Followed by [a-zA-Z]
Followed by [a-zA-Z0-9_] — 0 or more times
And it cannot end with _

I have implemented this solution:

_*[a-zA-Z][a-zA-Z0-9_]*[^_]$

This regex can detect variables like:
try_it
But it cannot detect variables like:
x, y, z

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

This regex will be used for lexical analysis

Acceptable:

a100__version_2
_a100__version2
x
y
z

Non acceptable:

100__version_2
a100__version2_
_100__version_2
a100--version-2

>Solution :

This one may come in handy for matching your accepted words:

^_?[a-zA-Z](?:[a-zA-Z0-9_]+[^_])?$

Regex Explanation:

  • ^: start of string symbol
  • _?: an optional underscore
  • [a-zA-Z]: a letter
  • (?:[a-zA-Z0-9_]+[^_])?: an optional set of characters that doesn’t end with an underscore
  • $: end of string symbol

Check the demo 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