Reputation: 39
I am trying to validate that there NO spaces between two characters (or in the middle of a name) in a string.
I want a regex that will accept " ab " and reject " a b " .
I tried using "\\s*((_[a-zA-z]+)|([a-zA-Z]+[a-zA-Z0-9]*))\\s*"
and "(\\s*\\S\\s*)"
.
p.s I don't care about spaces before and after the character\word.
Thanks in advance!
Upvotes: 1
Views: 2725
Reputation: 2852
Try ^\s*\w+\s*$
This looks for zero or more spaces then any word characters [a-z0-9_]
then zero or more spaces again before the end of the string
Upvotes: 1
Reputation: 37404
you can use \\s*\\S+\\s*
`
\\s*
match zero or more spaces\\S+
match one or more non-space characters\\s*
match zero or more spaces
System.out.println(" aa ".matches("\\s*\\S+\\s*")); // true
System.out.println(" a bc ".matches("\\s*\\S+\\s*")); // false
Note : matches
implicitly include starting of match ^
and ending of match $
anchors and there is no need of capturing group ()
unless you are trying to fetch the specified match out of your data.
To match only alphabets use \\s*[a-zA-Z]+\\s*
Upvotes: 2
Reputation:
You can match exactly N characters with {N}
So, you can just use:
\\S{2}
which matches any two non-whitespace characters; or
\\w{2}
which matches two word characters.
[a-zA-Z]{2}
two letters, etc.
Upvotes: 0