I'm trying to match Strings up to a certain size which do not only consist of certain characters.
So for the first part it's rather easy. To match this:
Yes: "abcde / asbas"
Yes: "abcde/ asbas"
Yes: "abcde/ ///"
Yes: " ///aasd"
Yes: "/// aasd"
Yes: "avcdesc"
No: "AVASD/ASDB"
I use this expression:
[ \/a-z0-9]{1,20}
But this would also match something like this: " ////"
As I want to avoid this I tried to add another expression and combine them using Lookahead:
(?=(?![ \/] $))(?=[ \/a-z0-9]{1,20}).*$
This works regarding avoiding the previous example " ////"
But somehow everything character after valid characters is ignored, so the following behavior occurs:
A String like this "asdad988AAA"
is matched.
As explained, this is not intended. Maybe someone has an idea on how to solve this.
Thanks.
Regex101: https://regex101.com/r/nmSMMu/1
CodePudding user response:
You can use
^(?=[ \/]*[a-z0-9])[a-z0-9\/ ]{1,20}$
See the regex demo. Details:
^
- start of string(?=[ \/]*[a-z0-9])
- there must be a lowercase ASCII letter or digit after any zero or more spaces or/
chars[a-z0-9\/ ]{1,20}
- one to twenty lowercase ASCII letters, digits,/
or spaces$
- end of string.