I’m trying to print out a pattern from a string.
String stringToProcess = "Test Test Hello World Test Test";
String pattern = "Hello\\sWorld";
System.out.println(stringToProcess.substring(stringToProcess.indexOf(pattern), stringToProcess.lastIndexOf(pattern)));
When I run this code it seems to give lots of errors depending on how I try to change it and repair it. As it is above, it gives the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Please note: I already am aware of the Pattern.compile(regex, Pattern); way of doing this. I would like to do it in a different way.
Here is your requested example:
Beacause you really wanted to use
\\sinstead of a blank, it will also matchHello\tWorld,Hello\nWorldand all other possible single whitespace character between Hello and World.The way I have it written it will only print the first found match (if there is one), if you want of print all matches to your pattern replace
ifwithwhile.But I wouldn’t use
start(),end()andsubstring()if I didn’t have to, you can just printmatcher.group()if you want to print your match.