0

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.

7
  • 5
    indexOf() doesn't work with regex, see the documentation Commented Dec 13, 2012 at 7:48
  • 2
    The only other way I am aware of is to use Matcher.start() .... but that involves Pattern.compile(regex, Pattern) which you already know. Commented Dec 13, 2012 at 7:50
  • use the Pattern and Matcher and use start() and end() (also your \s should be \\s. Commented Dec 13, 2012 at 7:50
  • Could you possibly post an example in an answer? Commented Dec 13, 2012 at 7:51
  • Why don't you just use String pattern = "Hello World";? I.e. you don't need a regex to define a a space symbol. Commented Dec 13, 2012 at 7:52

2 Answers 2

0

Here is your requested example:

    String stringToProcess = "Test Test Hello World Test Test";
    String patternString = "Hello\\sWorld";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(stringToProcess);
    if (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();
        System.out.println(stringToProcess.substring(start, end));
    }

Beacause you really wanted to use \\s instead of a blank, it will also match Hello\tWorld, Hello\nWorld and 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 if with while.

But I wouldn't use start(), end() and substring() if I didn't have to, you can just print matcher.group() if you want to print your match.

Sign up to request clarification or add additional context in comments.

Comments

0

This is function that return the start location of the sentence :

public  static int decodeString(String msg,String sentence) {
        Pattern p = Pattern.compile("(.*)"+sentence+"(.*)");
        Matcher m = p.matcher(msg);
        if (m.matches()) {
           return  m.end(1);
        }
        return -1;
    }

Note that this give the last matching. If we have some matches we need to work with loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.