The reason you get the error is that the split
method understands its argument as a regex, and all the characters in your prefix and suffix are actually special characters in regex.
There are ways to escape special characters, but in this case, there is really no need to use the regex-based split
method for this particular requirement. It is actually not the right tool. Just extract the word from within the pattern using substring
, as you know exactly where it starts and where it ends:
class Test {
public static final String PREFIX = "^((?!";
public static final int PREFIX_LEN = PREFIX.length();
public static final String SUFFIX = ").)*$";
public static final int SUFFIX_LEN = SUFFIX.length();
public static String extractWord( String arg ) {
if (arg.startsWith(PREFIX) && arg.endsWith(SUFFIX)) {
return arg.substring(PREFIX_LEN, arg.length() - SUFFIX_LEN);
}
return null;
}
public static void main( String[] args ) {
System.out.println( extractWord("^((?!PATT).)*$") );
}
}
This tells it to extract the part of the string that starts after the PREFIX ends, and ends at the beginning of the SUFFIX.