vuhung3990
vuhung3990

Reputation: 6829

how to translate regula expression from php to java

php code

$contentHtml = ".....";
preg_match('/;ytplayer\.config\s*=\s*({.*?});/', $contentHtml, $matches);
var_dump($matches[1]);

how to using this expression on java/android ?

Pattern pattern = Pattern.compile("/;ytplayer\.config\s*=\s*({.*?});/");
// error: Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )

thank you.

Upvotes: 0

Views: 127

Answers (2)

hwnd
hwnd

Reputation: 70732

In Java, you don't use delimiters for your regular expression and you need double backslashes.

Pattern pattern = Pattern.compile(";ytplayer\\.config\\s*=\\s*(\\{.*?\\});");

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Java regex would be,

Pattern pattern = Pattern.compile(";ytplayer\\.config\\s*=\\s*(\\{.*?});");

You don't need to use php regex delimiters in Java. That is starting / and ending / symbol. And you have to escape \ one more time in java.

Example:

String s = ";ytplayer.config = {foo bar};";
Pattern regex = Pattern.compile(";ytplayer\\.config\\s*=\\s*(\\{.*?});");
 Matcher matcher = regex.matcher(s);
 while(matcher.find()){
        System.out.println(matcher.group(1));
}

Output:

{foo bar}

Upvotes: 1

Related Questions