0

Can anyone please suggest a regex for the below mentioned conditions.

  1. Should not allow only blank spaces(white spaces).
  2. Blank spaces are allowed only if atleast one non whitespace character is present.
  3. Any characters is allowed.
  4. Length should be limited to 50 characters.

I tried this pattern .*[^ ].* from Regex pattern for "contains not only spaces". Can you please suggest how to limit this to 50 characters.

Ashwin Shirva
  • 1,331
  • 1
  • 12
  • 31

2 Answers2

1

I suppose lookahead in regex can help out.

Try adding (?=.{0,50}$) in front of your regex. To have something like this:

(?=.{0,50}$)^.*[^ ].*

You may change the the {0,50} to {1,50} if you don't want to allow empty strings.

owsega
  • 96
  • 7
  • This works perfectly with java. Do you have an equivalent Go lang solution? Because lookaheads don't work with golang – Ashwin Shirva May 18 '18 at 10:32
  • Unfortunately I don't know Go. Without lookahead you may need to write additional code – owsega May 18 '18 at 10:40
  • Is there a way to do this without a lookahead? – Ashwin Shirva May 18 '18 at 10:43
  • Yes, but it involves 50 alternations. `(\S.{,49}|.\S.{,48}|.{2}\S.{,47}|...)` – Sebastian Proske May 18 '18 at 10:48
  • Yes, it is possible, but you won't like it: you will have to spell out each possible variation. So, for a string with 3 char limit, it would look like `^( {2}\S| \S |\S )$`. Imagine what the expression for 50 chars will look like. Certainly you may create it dynamically, but why not just use `(len(s) <= 50 || len(s) >= 0) && len(strings.TrimSpace(s)) != 0`? – Wiktor Stribiżew May 18 '18 at 10:53
0

You can't use lookarounds in Go regex patterns. In Java, to match a non-blank string with 0 to 50 chars, you may use

s.matches("(?s)(?!.{51})\\s*\\S.*")

The pattern matches the whole string (matches anchors the match by default) and means:

  • (?s) - Pattern.DOTALL inline modifier making . match newlines, too
  • (?!.{51}) - a negative lookahead disallowing 51 chars in the string (so, less than 51 is allowed, 0 to 50, it is equal to (?=.{0,50)$)
  • \\s* - 0+ whitespaces
  • \\S - a non-whitespace char
  • .* - any 0+ chars to the end of the string.

In Go, just use a bit of code. Import strings and use

len(s) <= 50 && len(s) >= 1 && len(strings.TrimSpace(s)) != 0

Here, len(s) <= 50 && len(s) >= 1 limit the string length from 1 to 50 chars and len(strings.TrimSpace(s)) != 0 forbids an empty/blank string.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563