Home > Back-end >  Couldnt write a regex to string
Couldnt write a regex to string

Time:08-04

I have string like that test_i|min:10|sym:iterator. First part is a name and always will be, other parts is optional. Regex need to test string like it and if it bad (like min:10|sym:iterator or test_i|min:10sym:iterator or test_i|min:|sym:iterator etc) return false from test method(regex.test(string)). How regex fits?

CodePudding user response:

You want something like this to match:

test_i|min:10|sym:iterator

So some identifier, then some key and a value.

You want this to not match:

  • min:10|sym:iterator (No identifier at the beginning)
  • test_i|min:10sym:iterator (| missing between two key/values)
  • test_i|min:|sym:iterator (missing value)

Using this regular expression will only accept your first test case and excludes the rest:

^\w (\|\w :(\d |\w ))*$
  • ^ and $ means your expression must match all of the input text
  • \w just expects any name at the start
  • \| is the | symbol (must be escaped as explained in the comments)
  • \w :(\d |\w ) makes sure the value is either a number or a string
  • ()* repeats this pattern for as many matches as there are

See regex101 playground here to experiment:
https://regex101.com/r/ncllOW/1

  • Related