varan
varan

Reputation: 354

Java regex with ^ symbol: find from position

I'm trying to find ^a{3} pattern in string, but not from beginning. From position 2

For example:

Pattern pattern = Pattern.compile("^a{3}");
Matcher m = pattern.matcher("xxaaa");
System.out.println(m.find(2));

It seems ^ means start of the string (not start of string from position 2)

But how to find pattern from position 2 and be sure that a{3} starts in this position

Upvotes: 2

Views: 796

Answers (3)

black panda
black panda

Reputation: 2991

You can change the region in your Matcher to start at 2 without messing around with the original regex. See below:

Pattern pattern = Pattern.compile("^a{3}");
Matcher m = pattern.matcher("xxaaa");
m.region(2, m.regionEnd()); // <---- region start is now 2

System.out.println(m.find());
System.out.println(m.lookingAt());

See: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#region-int-int-

Upvotes: 1

ergonaut
ergonaut

Reputation: 7057

This would work:

(?<=.)\^a{3}

(?=  # lookbehind
.    # any character
)    # close
\^a{3} # your pattern

See https://regex101.com/r/jTLwUp/1

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163277

You might use a positive lookbehind (?<=:

(?<=^..)a{3}

That would match:

(?<= # Positive lookbehind which asserts that what is before is
  ^  # Beginning of the string
  .. # Match 2 times any character
)    # Close lookbehind
a{3} # Match aaa

Output Java test

Upvotes: 1

Related Questions