Find all words with 3 letters with regex

2020-01-31 04:06发布

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

This is my expression:

^[a-zA-Z]{3}$

I tested it with different online regex tester, but none of them matched my expression.

3条回答
我想做一个坏孩纸
2楼-- · 2020-01-31 04:19

you can use . instead of [a-zA-Z] if you want to match any character (also numbers):

 \b.{3}\b
查看更多
我只想做你的唯一
3楼-- · 2020-01-31 04:19
  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<String> sentence = new ArrayList<String>();
        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());
            }
        }
    }
    
查看更多
Luminary・发光体
4楼-- · 2020-01-31 04:31

You should use your match with word boundaries instead of anchors:

\b[a-zA-Z]{3}\b

RegEx Demo

When you use:

^[a-zA-Z]{3}$

It means you want to match a line with exact 3 letters.

查看更多
登录 后发表回答