Reputation: 256
I am using java and am trying to write a regex that excepts this:
jkdsl;a asdfasdf asdfjkl;
and this
789u 13789u
but not this
HJKs9
or this
hiop hiopwer rewk3 fheio2
So far I have this, but it doesn't seem to work (I have used an online regex tester):
(\S+\s){2,3}
I think:
\S+ means more than one non space
\s means a whitespace
(X){2,3} means 2-3 (inclusive) consecutive occurrences of X
Where have I gone wrong?
(I have put it in java as "(\\S+\\s){2,3}"
as \ is an escape)
Upvotes: 1
Views: 209
Reputation: 174706
To match the lines which has two or three words.
^\S+(?:\s+\S+){1,2}$
Java regex would be,
^\\S+(?:\\s+\\S+){1,2}$
\S+
matches one or more non-space characters. \s+
matches one or more space characters. {1,2}
called repetition quantifier which repeats the previous token that is (?:\s+\S+)
one or two times. $
Asserts that we are at the end of the line.
OR
Use this if your input contains preceding or following spaces.
"^\\s*\\S+(?:\\s+\\S+){1,2}\\s*$"
Upvotes: 2