Reputation: 1292
I am having a string which can have a sentence containing symbols and numbers and also the sentence can have different lengths
For Example
String myString = " () Huawei manufactures phones"
And the next time myString can have the following words
String myString = " * Audi has amazing cars &^"
How can i use regex to get the first word from the string so that the only word i get in the first myString is "Huawei" and the word i get on the second myString is Audi
Below is what i have tried but it fails when there is a space before the first words and symbols
String regexString = myString .replaceAll("\\s.*","")
Upvotes: 1
Views: 816
Reputation: 785058
You may use this regex with a capture group for matching:
^\W*\b(\w+).*
and replace with: $1
Java Code:
s = s.replaceAll("^\\W*\\b(\\w+).*", "$1");
RegEx Details:
^
: Start\W*
: Match 0 or more non-word characters\b
: Word boundary(\w+)
: Match 1+ word characters and capture it in group #1.*
: Match anything aftereardsUpvotes: 2