Home > OS >  Regex to enforce a specific pattern
Regex to enforce a specific pattern

Time:03-31

I want to validate a string which should follow a specific defined pattern.

Rule are

  • it should starts with any of this three words 'Dev', 'Tweak' or 'Feature'
  • then should have a space hyphen and space i.e., -
  • and three or word followed by a period. (also it can have URL or '#' or punctuators)

rules img

So I have written a regex like this, but some how it is not working

^((Tweak|Dev|Feature)(\s-\s)(\w{3,})(\.))$

Here is the regex playground URL: https://regex101.com/r/136LCG/1

The regex should match following strings

  1. Tweak - this should be correct.
  2. Feature - my feature having a special character as #123.
  3. Dev - this should also work https://regex101.com/
  4. Dev - this is my message. Ref projectname#123.
  5. Dev - my message having long sentence, with additional punctuators.

CodePudding user response:

You can use

^(?:Tweak|Dev|Feature)\s -(?:\s (?:#?\w |http\S*)){3,}\.?$

See the regex demo. Details:

  • ^ - start of string
  • (?:Tweak|Dev|Feature) - one of three words
  • \s - one or more whitespaces
  • - - a hyphen
  • (?:\s (?:#?\w |http\S*)){3,} - three or more repetitions of
    • \s - one or more whitespaces
    • (?:#?\w |http\S*) - either of
      • #?\w - an optional # char and then one or more letters, digits or underscores
      • | - or
      • http\S* - http and then zero or more non-whitespaces
  • \.? - an optional .
  • $ - end of string.

NOTE: POSIX ERE does not allow using non-capturing groups, and depending on where you are using it, it might not be possible to use \s and \w shorthannd character classes. So, in POSIX ERE, the regex will look like

^(Tweak|Dev|Feature)[[:space:]] -([[:space:]] (#?[[:alnum:]_] |http[^[:space:]]*)){3,}\.?$

Details:

  • All non-capturing groups are replaced with capturing ones, (?:...) with (...)
  • \s turned into [[:space:]]
  • \S turned into [^[:space:]]
  • \w turned into [[:alnum:]_]
  • Related