其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

如何将正则表达式从php转换为java

GG网络技术分享 2025-03-18 16:15 1


问题描述:

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

\\f \\\" \\\' \\\\ )

thank you.

图片转代码服务由CSDN问答提供

感谢您的意见,我们尽快改进~

功能建议

php code </ p>

  $ contentHtml =“....  。; 

\\ /

\'/; ytplayer \\ .config \\ s * = \\ s *({。*?}}; /\',$ contentHtml,$ matches);

var_dump($ matches [1]);

</ code> </ pre>

如何在java / android上使用这个表达式?</ p>

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

//错误:转义序列无效(有效转义序列为\\ b \\ t

\\ f \\”\\\'\\ \\ \\)<n </ code> </ pre>

谢谢。</ p>

</ div>

网友观点:

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}

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

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

PHP 基础知识 (正则表达式)

PHP中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。

变量名与PHP中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头,后面跟上任意数量的字母,数字,或者下划线。按照正常的正则表达式,它将被表述为:'[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*‘。

$this是一个特殊的变量,它不能被赋值。

基础

$开头,跟着字母或者下划线,后面可以是数字,甚至是中文。不过要按照命名规范,使用驼峰命名.

标签:

提交需求或反馈

Demand feedback