Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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
迭代匹配器正则表达式Java_Java_Regex_Match - Fatal编程技术网

迭代匹配器正则表达式Java

迭代匹配器正则表达式Java,java,regex,match,Java,Regex,Match,我希望给定一个输入字符串,迭代该字符串中包含模式的每个子字符串,然后将另一个模式应用于这些子字符串,并以某种方式替换该部分。 代码如下: public static String parseLinkCell1NoLost(String cell) { String link = cell; Pattern catPattern = Pattern.compile("\\{\\{(.*?)\\}\\}", Pattern.MULTILINE); Matcher match

我希望给定一个输入字符串,迭代该字符串中包含模式的每个子字符串,然后将另一个模式应用于这些子字符串,并以某种方式替换该部分。 代码如下:

public static String parseLinkCell1NoLost(String cell) {

    String link = cell;
    Pattern catPattern = Pattern.compile("\\{\\{(.*?)\\}\\}", Pattern.MULTILINE);
    Matcher matcher = catPattern.matcher(cell);
    while (matcher.find()) {
        Pattern newP = Pattern.compile("\\{\\{nowrap|(.*?)\\}\\}", Pattern.MULTILINE);
        Matcher m = newP.matcher(cell);

        if (m.matches()) {
            String rest = m.group(0);
            String prov = m.group(1);
            String[] temp = prov.split("\\|");
            if (temp == null || temp.length == 0) {
                return link;
            } else {
                link = link.replace(rest, temp[1]);
            }
        }

    }
    return link;
}
问题是我无法获得与每个
匹配器.find()匹配的子字符串。因此,如果我有like输入
“{{nowrap | x}}{{nowrap | y}}{/code>,我想迭代两次,第一次得到子字符串
{nowrap | x}
,第二次得到子字符串
{nowrap | y}
。 提前谢谢

public static String parseLinkCell1NoLost(String cell) {
    String link = cell;
    Pattern catPattern = Pattern.compile("\\{\\{(.*?)\\}\\}", Pattern.MULTILINE);
    Matcher matcher = catPattern.matcher(cell);
    while (matcher.find()) {
        Pattern newP = Pattern.compile("\\{\\{nowrap\\|(.*?)\\}\\}", Pattern.MULTILINE);
        Matcher m = newP.matcher(matcher.group(0));

        if (m.matches()) {
            String rest = m.group(0);
            String prov = m.group(1);
            link = link.replace(rest, prov);
        }
    }
    return link;
}
两个小错误:

  • 在循环中,您应该使用
    matcher.group(0)
    在每次迭代中仅使用您的匹配,而不是整个单元格
  • 您需要在正则表达式中转义
    |
    符号
  • 纠正后,也可以模拟更换(..)

不,这不好,我必须对每个子字符串应用不同的模式newP。对不起,我不明白您在做什么。newP模式包含冗余的
模式。多行
(您可以将其删除)和创建替换的未替换的
|
<代码>\\{nowrap}(.**?\\\\\\}}
匹配
{nowrap
或除换行符以外的任何0+字符,然后匹配
}
。你是想逃出
|
“{nowrap | x}{{nowrap | y}}{/code>的输出是什么?好的,我首先在while中用{…}检查每个子字符串,然后在while中检查其他正则表达式,如{nowrap |}或{birth | 16 | 09 | 1991},并正确处理它们。