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

using regex to verify if character before dot is even or odd number

I’m trying to figure out if my problem is solvable using regex.

I have computer name in format computer01.domain.com.

I’d like to check if number before first dot is odd or even number.

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 managed to build regex to locate first character before dot ^([^.])+(?=\.) now I can’t figure out how to check if it’s odd or even.

>Solution :

If you want to know wether ther is an even or odd number, you might use 2 capture groups with an alternation.

If the first capture group exists, it is an odd number, if the second one exists then it is an even number.

If you only want to capture the single digit, you can also match the following dot instead of asserting it.

^[^.]+(?:([13579])|([02468]))\.

The pattern matches:

  • ^ Start of string.
  • [^.]+ Match 1+ times any char other than a dot
  • (?: Non capture group
    • ([13579]) Capture an odd number in group 1
    • | Or
    • ([02468]) Capture an even number in group 2
  • ) Close the non capture group
  • \. Match the dot

Regex demo

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