简体   繁体   中英

Find words with 3 letters in Java

I want to find all words with 3 letters in every element.

In this post I found the right regex, but know I'm trying to get it work in Java.

Set<String> input = new HashSet<String>();
input.add("cat 123");
input.add("monkey");
input.add("dog");

Pattern p = Pattern.compile("\b[a-zA-Z]{3}\b");

for (String s : input) {
    if (p.matcher(s).matches()) {
        System.out.println(s);
    }
}

In my case I want cat and dog to be put out, but I only get an empty output.

  1. You have to escape the backslashes, ie \\\\b instead of \\b :

     Pattern p = Pattern.compile("\\\\b[a-zA-Z]{3}\\\\b"); 
  2. Create a matcher and use find and group to find and show the next matched group:

     for (String s : input) { Matcher m = p.matcher(s); while (m.find()) { System.out.println(m.group()); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM