Find the words start from a special character java

后端 未结 5 1639
梦毁少年i
梦毁少年i 2021-02-08 21:18

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 # yo

相关标签:
5条回答
  • 2021-02-08 21:48

    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
    
    0 讨论(0)
  • 2021-02-08 21:49
         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 讨论(0)
  • 2021-02-08 21:58

    Try this expression:

    # *(\w+)
    

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

    0 讨论(0)
  • 2021-02-08 21:59

    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("#")

    0 讨论(0)
  • 2021-02-08 22:02

    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 #
      }
    }
    
    0 讨论(0)
提交回复
热议问题