namalfernandolk
namalfernandolk

Reputation: 9134

Charat operator outside the square brackets in regex java

I have three patterns

Pattern pattern = Pattern.compile("[a-f]"); // Pattern 1
//Pattern pattern = Pattern.compile("[^a-f]");// Pattern 2
//Pattern pattern = Pattern.compile("^[a-f]");// Pattern 3

Matcher matcher = pattern.matcher("acdefghijklmn");
while(matcher.find()) {
    System.out.print(matcher.start() + " ");
}

Results :
Pattern 1 - 0 1 2 3 4
Pattern 2 - 5 6 7 8 9 10 11 12
Pattern 3 - 0

I know Pattern 1 is for finding any simple letter between a and f(inclusive) and Pattern 2 is for finding any simple letter not between a and f (inclusive). But what does pattern 3 mean?

Upvotes: 0

Views: 426

Answers (3)

René Link
René Link

Reputation: 51423

But what does pattern 3 mean?

Pattern 3 ^[a-f] macthes when a string starts ^ with [a-f].

Upvotes: 1

anubhava
anubhava

Reputation: 785541

"^[a-f]"

Means letter a-f is matched at the line start.

Recommended Regex Reference

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533670

But what does pattern 3 mean?

^ outside the [] means at the start of the String just like $ means at the end.

Upvotes: 2

Related Questions