Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于php代码在Java中使用正则表达式_Java_Php_Regex - Fatal编程技术网

基于php代码在Java中使用正则表达式

基于php代码在Java中使用正则表达式,java,php,regex,Java,Php,Regex,我一直在php中使用这个 preg|u match_all(“| is”,$xx,$matches,preg|u SET_ORDER) 其中$xx是整个网页内容的字符串,用于查找所有匹配项 这将$matches设置为一个二维数组,然后我可以根据$matches的长度使用for语句循环遍历该数组,例如 $匹配[$i][1]哪一个将是第一个(.*) $matches[$i][2]第二个(.*) 等等 我的问题是如何在java中复制这一点? 我一直在阅读关于java正则表达式的教程和博客,并一直在使用

我一直在php中使用这个

preg|u match_all(“| is”,$xx,$matches,preg|u SET_ORDER)

其中$xx是整个网页内容的字符串,用于查找所有匹配项

这将$matches设置为一个二维数组,然后我可以根据$matches的长度使用for语句循环遍历该数组,例如

$匹配[$i][1]
哪一个将是第一个
(.*)

$matches[$i][2]
第二个
(.*)

等等

我的问题是如何在java中复制这一点? 我一直在阅读关于java正则表达式的教程和博客,并一直在使用模式和匹配器,但似乎无法理解。而且,matcher什么也没找到。因此,我的
while(matcher.find())
是无效的,通常会抛出一个错误,表示尚未找到匹配项

这是我的java代码,要匹配的模式是

String pattern = new String(
    "<a href=\"http://www.example.com/photoid/(w+)\"><img src=\"(w+)\" alt=\"(w+)\" /></a>");
String模式=新字符串(
"");
我也试过

String pattern = new String(
    "<a href=\"http://www.example.com/photoid/(.*?)\"><img src=\"(.*?)\" alt=\"(.*?)\" /></a>");
String模式=新字符串(
"");

String模式=新字符串(
"");

没有找到匹配项。

不是Java专家,但是字符串不应该转义双引号和转义符吗

 "<a href=\"http://www.mysite.com/photoid/(.*?)\"><img src=\"(.*?)\" alt=\"(.*?)\" /></a>"
 or
 "<a\\ href=\"http://www.mysite.com/photoid/(.*?)\"><img\\ src=\"(.*?)\"\\ alt=\"(.*?)\"\\ /></a>"
“”
或
""

您发布的正则表达式为我工作,因此您的错误可能在于如何使用它:

String test = "<html>\n<a href=\"http://www.mysite.com/photoid/potato.html\"><img src=\"quack-quack\" alt=\"hi\" /></a>\n</html>";
// This is exactly the pattern code you posted :
String pattern = new String(
    "<a href=\"http://www.mysite.com/photoid/(.*?)\"><img src=\"(.*?)\" alt=\"(.*?)\" /></a>");

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(test);
m.find(); // returns true
String test=“\n\n”;
//这正是您发布的模式代码:
字符串模式=新字符串(
"");
Pattern p=Pattern.compile(Pattern);
匹配器m=p.匹配器(测试);
m、 查找();//返回true

查看如何使用此选项。

检查此@FaceOfJock您认为我应该使用(\w+)而不是(.*)@TonyCruze吗?我意识到www.mysite.com只是一个示例,但如果您还没有这样做,您应该更新您的正则表达式,以引用不应解释为正则表达式的文本
www.mysite.com
也将匹配
wwwemysite.com
。是的,我相信我是正确逃脱的。如果不转义引号,它就不会编译。我将用我正在使用的实际模式更新问题。是的!我刚想出来。就这样!
String test = "<html>\n<a href=\"http://www.mysite.com/photoid/potato.html\"><img src=\"quack-quack\" alt=\"hi\" /></a>\n</html>";
// This is exactly the pattern code you posted :
String pattern = new String(
    "<a href=\"http://www.mysite.com/photoid/(.*?)\"><img src=\"(.*?)\" alt=\"(.*?)\" /></a>");

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(test);
m.find(); // returns true