tags:

views:

41

answers:

2

I am converting from .NET to Java and the following .NET Regular expression fails.

(?<before>.{0,10})" + mSearchTerm + "(?<after>.{0,255})

There are 2 named groups here, but the named part is not important to me.

+2  A: 

The named groups are the only thing I see that won't work in Java, but you seem to have left off some quotation marks. Try this:

Pattern p = Pattern.compile("(.{0,10})" + mSearchTerm + "(.{0,255})");
Alan Moore
May be there are more chars than the op want to catch before the first and after the last quote
M42
+1  A: 

In addition to the answer given by Alan Moore, the upcoming jdk7 will support named groups in regular expressions. See http://download-llnw.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html for details.

Also, if you are building a regex from a searchstring that is not a regex itself, it would be better to use Pattern.quote(searchString), so that all special characters are properly escaped.

Jörn Horstmann