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!
$ 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.
In Java, "\b" is a back-space character (char 0x08 ), which when used in a regex will match a back-space literal.
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.
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+");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With