ollie299792458
ollie299792458

Reputation: 256

Regex, how to recognise 2 or 3 words (of any non space) delimited by spaces

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:

Where have I gone wrong?

(I have put it in java as "(\\S+\\s){2,3}" as \ is an escape)

Upvotes: 1

Views: 209

Answers (1)

Avinash Raj
Avinash Raj

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*$"

DEMO

Upvotes: 2

Related Questions