skip to Main Content

I am writing a regular expression which has multiple permutations and combinations. I did write the regex individually but how to combine them to make it a single regex. Please guide.

Allowed strings:

  • combination of alphabets and numbers
  • can have space in between
  • can have special characters at start, end and in between also (cannot have # + ,)
  • allowed examples for reference dfg, rt534, 34dfg, dfg(space)564(space)dfg545, !sdf7&*

Not allowed strings

  • cannot have space at start and end
  • cannot have # + , anywhere in the string
  • cannot start with number but can be followed by an alphabet
  • Ex: allowed – 445fsdf
  • Ex: not allowed – 4
  • not-allowed examples for reference 345, (space)sdfs, sdfsdf(space), #df8, sdfsdf(comma)4534

The individual regex I have are

^[A-Za-z0-9]*$
[^#+\,]
^[^s]+(s+[^s]+)*$

Please guide me in combining the regular expressions.

3

Answers


  1. If you want to replicate logical AND with regex, there is a bigger answer, which I won’t attempt to replicate. Please read Regular Expressions: Is there an AND operator?

    However, if you want to replicate logical OR with regex you could use alternation like this:

    (patternA | patternB | patternC)
    

    e.g.

    (^[A-Za-z0-9]*$ | [^#+\,] | ^[^s]+(s+[^s]+)*$)
    

    A very concise summary of this operator (from the linked reference) is: "it tells the regex engine to match either everything to the left of the vertical bar, or everything to the right of the vertical bar."

    Login or Signup to reply.
  2. You could use this regex, which combines the conditions that you state in the question:

    ^(?! )(?!.*s$)(?=.*[a-zA-Z])[^#+\,]+$
    

    It matches a string which:

    • (?! ) : doesn’t start with (space)
    • (?!.* $) : doesn’t end with (space)
    • (?=.*[a-zA-Z]) : contains at least one alphabetic character
    • [^#+\,]+ : consists only of characters not including #, +, or ,

    Regex demo on regex101. Note for the purposes of the demo I had to include n in the inverted character class to prevent matching text over line boundaries.

    Login or Signup to reply.
  3. My understanding of the rule (long story short):

    • The string should not include any character of #+,.
    • The string should not start with a digit or a space character.
    • The string should not end with a space character.

    Then the corresponding regex will be:

    ^[^0-9#+\,s][^#+\,n]*[^#+\,s]$
    

    Demo

    Btw the shown example 34dfg should not be allowed as it starts with a digit.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search