开发者

Find the words start from a special character java

I want to find the words that start with a "#" sign in a string in java. There can be spaces between the sign and the word as well.

The string "hi #how are # you" shall give the output as :

how
you

I have tried this with regex, but still could not find a suitable pattern. Pl开发者_JAVA技巧ease help me on this.

Thanks.


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

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 out:

how
you


I think you may be best off using the split method on your string (mystring.split(' ')) and treating the two cases separately. Regex can be hard to maintain and read if you're going to have multiple people updating the code.

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


Try this expression:

# *(\w+)

This says, match # then match 0 or more spaces and 1 or more letters


Here's a non-regular expression approach...

  1. Replace all occurrences of a # followed by a space in your string with a #

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

  2. NOw split the string into tokens using the space as your delimited character

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

  3. Finally iterate over your words and check for the leading character

    word.startsWith("#")


     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:)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜