Anh Minh Nguyễn
Anh Minh Nguyễn

Reputation: 13

How to find words having given letter using Java Regex

public class Homework {

  public static void main(String[] args) {

    String words[] = { "Abendessen", "Affe", "Affen", "aber", "anders", "Attacke", "arrangieren", "Art", "Asien",
            "Bund", "Arten", "Biene", "Abend", "baden", "suchen", "A1rten", "Abend-Essen" };

    Pattern pattern = Pattern.compile("[aA][a-z[n]+a-z]*");

    for (int i = 0; i < words.length; i++) {
      Matcher matcher = pattern.matcher(words[i]);
      if (matcher.find()) {
        System.out.println("OK: " + words[i]);
      }
    }
  }
}

Filters for words beginning with a or A and having an n in the word. These words may only consist of letters and have only small letters starting with the second letter. These words should be matched: Abendessen, Affen, anders, arrangieren, Asien, Arten, Abend

I've tried this regular expression above carelessly and believe that's wrong too.

Upvotes: 1

Views: 65

Answers (1)

The fourth bird
The fourth bird

Reputation: 163287

Your current pattern [aA][a-z[n]+a-z]* reads as:

Character class [aA], character class [a-z[n]+. It is then followed by a-z]* which will match an a, -, z and ] repeated 0+ times.

That would for example match Abendessena-z]

What you might do is to start the match with a or A and repeat 2 times [a-z] 0+ times and make sure that there is a n in the middle:

\b[aA][a-z]*n[a-z]*\b

Explanation

  • \b Word boundary
  • [aA] Match a or A
  • [a-z]* Match 0+ times a-z
  • n Match n
  • [a-z]* Match 0+ times a-z
  • \b Word boundary

You might also use anchors ^ and $ to assert that start and the end of the string instead of \b

Regex demo

Upvotes: 1

Related Questions