我试图从字符串中打印出一个模式。在字符串中查找正则表达式
String stringToProcess = "Test Test Hello World Test Test";
String pattern = "Hello\\sWorld";
System.out.println(stringToProcess.substring(stringToProcess.indexOf(pattern), stringToProcess.lastIndexOf(pattern)));
当我运行此代码时,它似乎给出了很多错误,具体取决于我如何尝试更改并修复它。由于它的正上方,它给人的错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
请注意:我已经很清楚这样做的Pattern.compile(regex, Pattern);
方式。我想以不同的方式做到这一点。
'indexOf()'不适用于正则表达式,参见[documentation](http://docs.oracle.com/javase/7/docs/api/ java/lang/String.html#indexOf(java.lang.String)) – jlordo
有没有办法解决它? – ThreaT
我知道的唯一的另一种方式是使用'Matcher.start()'....但涉及'Pattern.compile(正则表达式,模式)',你已经知道。 – NawaMan