I have a Java pattern I would like to match. I want to take my initial pattern an match the first occurrence of it. However, I consider
public static void main(String[] args)
{
final String expression = "(\\s*(a{1}\\s*b{1})\\s*)";
Scanner scanner1 = new Scanner(" ab");
//should be rejected
Scanner scanner2 = new Scanner开发者_开发问答("cab");
System.out.println(scanner1.findWithinHorizon(expression, 0));
System.out.println(scanner2.findWithinHorizon(expression, 0));
}
When I run the above code, I get the following output:
ab
ab
I've tried modifying the pattern to use reluctant and possessive quantifiers, but neither seem to produce the results I expect. What am I doing wrong here?
I assume you want to only match " ab" and not "cab" or "c ab", so use this regex to start at the beginning of the string: final String expression = "^(\\s*(a{1}\\s*b{1})\\s*)";
If you want to also match "c ab" but not "cab" try this: final String expression = "((?<!\\w)\\s*(a{1}\\s*b{1})\\s*)";
精彩评论