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

Regular Expression: Ensure that if a string contains specified symbols, then they must be enclosed by

My regular expression needs to ensure that:

  1. It consists of letters, so this can be done with:
^[a-zA-Z]+$"
  1. [Question] The string also can contain dot(s) and/or comma(s) and/or hyphen(s) and they all must be enclosed by letters(e.g. a.a):
  • Right: a.bc-d.e (All the symbols are enclosed by letters)
  • Not Right: a..b (The first dot is not enclosed and so is the second)
  • Not Right: .a (The dot in on enclosed)

In case you are interested the regular expression will be in a JSON schema and will be validated by some enterprise machine:

{
   "type": "string",
   "pattern": "my-regular-expression"
}

I have tried lookahead and lookbehind etc. but I am noob in regular expressions and I have not reached needed results by myself.

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 :

You can use an optional repetition of one of the allowed characters using a character class followed by A-Za-z

^[a-zA-Z]+(?:[.,-][a-zA-Z]+)*$

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