Reputation: 2388
I need a regular expression to match only the first two words (they may contain letters , numbers, commas and other punctuation but not white spaces, tabs or new lines) in a string.
My solution is ([^\s]+\s+){2}
but if it matches something like :'123 word' *in '123 word, hello'*, it doesnt work on a string with just two words and no spaces after.
What is the right regex for this task?
Upvotes: 6
Views: 11737
Reputation: 20997
You have it almost right:
(\S+\s+\S+)
Assuming you don't need stronger control on what characters to use.
If you need to match both two words or only one word only, you may use one of those:
(\S+\s+\S|\S+)
(\S+(?:\s+\S+)?)
Upvotes: 5
Reputation: 15706
Instead of trying to match the words, you could split the string on whitespace with preg_split()
.
Upvotes: 2
Reputation: 44259
If you really only want to allow numbers and letters [^\s]
is not restrictive enough. Use this:
/[a-z0-9]+(\s+[a-z0-9]+)?/i
Upvotes: 1