Can anyone please suggest a regex for the below mentioned conditions.
I tried this pattern .*[^ ].*
from Regex pattern for "contains not only spaces". Can you please suggest how to limit this to 50 characters.
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.
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.