user679526
user679526

Reputation: 845

regular expression for not allowing white space at start

A regular expression to allow only alphabets and numbers and spaces only in between alphabets with a maximum size of 20.

([a-zA-Z0-9]+([\\s][a-zA-Z0-9]+)*){0,20}.

This does not allow white space at start, but it is not checking the max size condition. How can I change this regular expression?

Upvotes: 1

Views: 12164

Answers (3)

Code Jockey
Code Jockey

Reputation: 6721

All Sorts of ways to write this, and since you're using Java, why not use a Java regex "feature"? :D

String regexString = "(?<!\\s+)[\\w\\s&&[^_]]{0,20}";

Broken down, this says:

(?<!\\s+)  # not following one or more whitespace characters,
[          # match one of the following:
  \\w      # word character (`a-z`, `A-Z`, `0-9`, and `_`)
  \\s      # whitespace characters
  &&[^_]   # EXCEPT FOR `_`
]          # 
{0,20}     # between 0 and 20 times

It will match a-z, A-Z, 0-9, and white space, even though the \w would otherwise include underscores, the extra part there says NOT underscores - I think it's unique to Java... anyways, that was fun!

Upvotes: 3

FailedDev
FailedDev

Reputation: 26940

The regex below :

boolean foundMatch = subjectString.matches("(?i)^(?=.{1,20}$)[a-z0-9]+(?:\\s[a-z0-9]+)*$");

will match a string of 1 to 20 characters starting with an alphanumeric character followed by a single space and more alphanumeric characters. Note that the string must end with an alphanumeric character and not a space.

Upvotes: 0

tripleee
tripleee

Reputation: 189789

You are specifying 20 repetitions of the entire pattern. I am guessing you probably mean something like

[a-zA-Z0-9][\\sa-zA-Z0-9]{0,19}

If empty input should be allowed, wrap the whole thing in (...)?.

Upvotes: 5

Related Questions