Home > other >  Regular expression to check format string string:string any occurrence
Regular expression to check format string string:string any occurrence

Time:10-20

I am trying to build regex to match - Test get:all words:test

can start with a word then space and followed by any occurrence of word:word separated by space.

@"^[a-zA-Z] /s(^[a-zA-Z] :^[a-zA-Z] /s)*"

CodePudding user response:

You added extra start of string anchors, ^, inside the pattern, and you need to remove them for sure.

Besides, the whitespace patterns must be written as \s and the first \s must be moved inside the repeated group that should be converted into a non-capturing one ((?:...)) for better performance.

You can use

^[a-zA-Z] (?:\s [a-zA-Z] :[a-zA-Z] )*$

See the regex demo. Details:

  • ^ - start of string
  • [a-zA-Z] - one or more ASCII letters
  • (?:\s [a-zA-Z] :[a-zA-Z] )* - zero or more repetitions of
    • \s - one or more whitespaces
    • [a-zA-Z] :[a-zA-Z] - one or more ASCII letters, :, one or more ASCII letters
  • $ - end of string (or use \z to match the very end of string).

If you meant to allow any word chars (letters, digits, connector punctuation) then replace each [a-zA-Z] with \w.

If you need to support just any Unicode letters, replace each [a-zA-Z] with \p{L}.

  • Related