1

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

fnax8902
  • 13
  • 5
  • You probably can use `^(?=.{1,20}$)[a-z0-9]+(?:[\/ ]+[a-z0-9]+)*$`, see [demo](https://regex101.com/r/6SuXFe/1). – Wiktor Stribiżew Apr 13 '22 at 19:53
  • First of all thanks! But strings leading with " /" or trailing with " /" or any mixture of it should be matched as well. I added some other examples: https://regex101.com/r/WQIGfm/1 – fnax8902 Apr 13 '22 at 20:10
  • So, you want `^(?=[ \/]*[a-z0-9])[a-z0-9\/ ]{1,20}$`? See [demo](https://regex101.com/r/WQIGfm/2). At least one lowercase letter or digit. – Wiktor Stribiżew Apr 13 '22 at 20:12
  • Can you explain the rules of what you actually want to match and what not a bit better? So far I think it is something like "only lowercase letters, no digits, space is ok but only one a time, / is ok but only once and only between either two spaces or two letters. Looks a bit confusing to me - do you have a better description? – cyberbrain Apr 13 '22 at 20:14
  • Ah yes sorry. So "only lowercase letters, digits, space or /, but not only space and /". – fnax8902 Apr 13 '22 at 20:18

1 Answers1

1

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563