Emmanuel Njorodongo
Emmanuel Njorodongo

Reputation: 1292

Regex to find the first word in a string java without using the string name

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

Answers (2)

anubhava
anubhava

Reputation: 785058

You may use this regex with a capture group for matching:

^\W*\b(\w+).*

and replace with: $1

RegEx Demo

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 aftereards

Upvotes: 2

g00se
g00se

Reputation: 4296

See how you get on with:

s = s.replaceAll("^[^\\p{Alpha}]*", "");

Upvotes: 0

Related Questions