1

I have a problem matching regex in Java, my text is:

Temperature: 9°C (48°F), Wind Direction: South South Westerly, Wind Speed: 19mph, Humidity: 87%, Pressure: 1018mb, Rising, Visibility: Good

My regex is

\bTemperature:[^,]*

The matching code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
  public static void main(String[] args) {
    Pattern p = Pattern.compile("\bTemperature:[^,]*");

    Matcher m = p.matcher("Temperature: 10°C (50°F), Wind Direction: South South Easterly, Wind Speed: 25mph, Humidity: 78%, Pressure: 1014mb, Falling, Visibility: Good");

    if(m.find())
    {
      System.out.println(m.group());
    }

  }
}

It does not output anything.

0

1 Answer 1

4

Try use Pattern p = Pattern.compile("\\bTemperature:[^,]*"); to escape.

As user John Bollinger said in the comment:

You need a backslash to be read and interpreted by the Pattern class, but backslashes in string literals are subject to interpretation by the Java compiler. The compiler converts a doubled backslash to a single backslash, just as Pattern requires.

The two backslashes will be compiled as one.

So when you reading the regex pattern string from file or console, you just need one backslash.

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

1 Comment

To clarify: you need a backslash to be read and interpreted by the Pattern class, but backslashes in string literals are subject to interpretation by the Java compiler. The compiler converts a doubled backslash to a single backslash, just as Pattern requires.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.