Android optional word boundary regex

767 Views Asked by At

I'm having trouble with a regular expression when targeting the Android platform 2.2.3.

The following regular expression works when targeting the Java VM on my desktop and the regular expression is also working on a .NET application too.

Pattern.compile("\\b?")

But when I target my phone I get a PatternSyntaxException. Any ideas?

1

There are 1 best solutions below

3
On

I can confirm that this does throw a PatternSyntaxException when running in the Android emulator, but not in a regular Java application. I can't see why that would be the case, other than the fact that regular expression implementation used in Android is different than in the normal Java SDK. From the Pattern Android Developers page:

The regular expression implementation used in Android is provided by ICU. The notation for the regular expressions is mostly a superset of those used in other Java language implementations. This means that existing applications will normally work as expected, but in rare cases Android may accept a regular expression that is not accepted by other implementations.

As a work-around, I did discover that you can get around the exception by enclosing the word boundary assertion in a non-capturing group.

Pattern.compile("(?:\\b)?");

(A capturing group works as well, but I doubt you need it.)

I suggest you report this as a bug to see if you can get an official response. (I already searched, and it doesn't appear to be reported yet.)