Find all words with 3 letters with regex

前端 未结 3 1132
有刺的猬
有刺的猬 2020-12-05 21:35

I\'m trying to find all words with 3 letters in a string.
So in this list

cat monkey dog mouse

I only want

cat dog
         


        
3条回答
  •  不知归路
    2020-12-05 22:07

    1. To match all words with 3 letters in a string, the pattern needs to be "\b[a-zA-Z]{3}\b"

    2. The next step would be to compile your pattern.

      Pattern pattern = Pattern.compile("\\b[a-zA-Z]{3}\\b");
      
    3. Use a matcher and use the find() and group() methods to print the occurrences

      for (String word : sentence) {
          Matcher matcher = pattern.matcher(word);
          while(matcher.find()) {
              System.out.println(matcher.group());
          }
      }
      
    4. Your program should look something like -

      public static void main(String[] args) {
          List sentence = new ArrayList();
          sentence.add("cat");
          sentence.add("monkey");
          sentence.add("dog");
          sentence.add("mouse");
      
          Pattern pattern = Pattern.compile("\\b[a-zA-Z]{3}\\b");
      
          for (String word : sentence) {
              Matcher matcher = pattern.matcher(word);
              while(matcher.find()) {
                  System.out.println(matcher.group());
              }
          }
      }
      

提交回复
热议问题