Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to get first two words of unknown length from a string

Tags:

java

regex

Say I have a string with various words of unknown length. I plan to split the string by using a regular expression. Something like:

String resString = origString.split(".*//s.*//s")[0];

What would be the regular expression to get the first two words? I was thinking .*//s.*//s, so all characters, followed by a space, then all characters, followed by another space. But using that gives me the exact same string I had before. Am I going about this the wrong way?

Any help would be appreciated!

like image 308
TookTheRook Avatar asked Nov 17 '10 22:11

TookTheRook


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is \b in Java regex?

In Java, "\b" is a back-space character (char 0x08 ), which when used in a regex will match a back-space literal.

How do you find a word inside of a string?

To find a word in the string, we are using indexOf() and contains() methods of String class. The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.


1 Answers

If you have only spaces between words, split by \\s+. When you split, the array would be the words themselves. First two would be in arr[0] and arr[1] if you do:

String[] arr = origString.split("\\s+");
like image 79
icyrock.com Avatar answered Sep 28 '22 06:09

icyrock.com