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
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:
e.g.
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."
You could use this regex, which combines the conditions that you state in the question:
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.My understanding of the rule (long story short):
#+,
.Then the corresponding regex will be:
Demo
Btw the shown example
34dfg
should not be allowed as it starts with a digit.