0

I am using a regex to extract the gold quotes from a webpage. I am parsing it to a string, then using regex to extract the quotes.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelloWorld{

 public static void main(String []args){
     String str = "----------------------------------------------------------------------"
                + "Metals          Bid        Ask           Change        Low       High "
                + "----------------------------------------------------------------------"
                + "Gold         1176.40     1177.40     -8.60  -0.73%    1171.90  1183.90";

    Pattern pattern = Pattern.compile("Gold(\\s{9})(\\d{4}).(\\d{2})");
    Matcher matcher = pattern.matcher(str);

    if (matcher.find())
    {
        System.out.println(matcher.group());
    }
    else {
        System.out.println("No string found");
    }

    }
}

This code finds the "Gold 1176.40" string that I want, but I can't save it as another string, as in

String temp = matcher.group();

How can I do this?

1
  • What do you mean by 'not being able to save it as another String'? Commented Jun 5, 2015 at 1:42

2 Answers 2

1

Declare a temp variable before the if condition and then append the matched string to that temp variable.

String temp = "";
Pattern pattern = Pattern.compile("Gold(\\s{9})(\\d{4})\\.(\\d{2})");
Matcher matcher = pattern.matcher(str);

if (matcher.find())
{
    temp = temp + matcher.group();
}
else {
    System.out.println("No string found");
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are interest do it in single line.

String str = "----------------------------------------------------------------------"
                + "Metals          Bid        Ask           Change        Low       High "
                + "----------------------------------------------------------------------"
                + "Gold         1176.40     1177.40     -8.60  -0.73%    1171.90  1183.90";
String s = str.substring(str.indexOf("Gold"))).replaceAll("(Gold\\s{9}\\d{4}.\\d{2}).*", "$1");

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.