Find words begin with a special character java

I want to find words that start with a "#" in a string in java. There may be spaces between the icon and the word.

The string "hi #how are # you" should "hi #how are # you" result as:

 how you 

I tried this with regex but couldn't find a suitable model. Please help me with this.

Thanks.

+7
source share
5 answers

Use #\s*(\w+) as your regular expression.

 String yourString = "hi #how are # you"; Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(yourString); while (matcher.find()) { System.out.println(matcher.group(1)); } 

This will print:

 how you 
+10
source

Try the following expression:

 # *(\w+) 

This says the match # matches 0 or more spaces and 1 or more letters

0
source

I think you might be better off using the split method in your line (mystring.split ('')) and handle the two cases separately. Regex can be difficult to maintain and read if you have several people updating the code.

 if (word.charAt(0) == '#') { if (word.length() == 1) { // use next word } else { // just use current word without the # } } 
0
source

This is not a regular expression ...

  • Replace all occurrences of # followed by a space in your line, C #

    myString.replaceAll ("\ s #", "#")

  • NOw split the string into tokens using space as a delimited character

    String [] words = myString.split ("")

  • Finally, iterating over your words and checking the leading character

    word.startsWith ("#")

0
source
  String mSentence = "The quick brown fox jumped over the lazy dog."; int juIndex = mSentence.indexOf("ju"); System.out.println("position of jumped= "+juIndex); System.out.println(mSentence.substring(juIndex, juIndex+15)); output : jumped over the its working code...enjoy:) 
-one
source

All Articles