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.
indexOf()doesn't work with regex, see the documentationMatcher.start().... but that involvesPattern.compile(regex, Pattern)which you already know.PatternandMatcherand usestart()andend()(also your\sshould be\\s.String pattern = "Hello World";? I.e. you don't need a regex to define a a space symbol.