0

I want to match an occurrence of 1 that comes after either the beginning of the String or a.

I've tried [\Aa]1, but this gives me a PatternSyntaxException.

2 Answers 2

2

Try a pattern like this:

(^|a)1

The ^ will match the begining of the string, while the a will match a literal Latin letter a. The | is called an alternation, and will match either the pattern on the left or the right, while parentheses restrict the scope of the alternation.

Now, this will include the a as part of the matched string. If you'd like to avoid this you can either use a lookbehind, like this:

(?<=^|a)1

This will match a 1, but only if it is immediately preceeded by the beginning of the string or a Latin letter a.

Sign up to request clarification or add additional context in comments.

2 Comments

@JoelA.Christophel You're absolutely right; I'm sorry. I just don't use that syntax at all, so I had forgotten it. I always use ^ just because it's easier for me to remember. I had assumed [\Aa] was an attempt to match a case insensitively. The reason why \A doesn't work inside a character class is that it's not actually a character, but a kind of zero-width assertion.
1

I am not sure if that is what you mean but maybe you are looking for something like

(?<=\\A|a)1

or if you are not using Pattern.MULTILINE flag

(?<=^|a)1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.