用条件用新行分割字符串

问题描述

仅当字符串不在我的“动作块”中时,我才尝试用\n分割字符串。
这是一个文本message\n [testing](hover: actions!\nnew line!) more\nmessage的示例,我想在\n不在[](this \n should be ignored)内时进行拆分,为此我制作了一个正则表达式,您可以在此处https://regex101.com/r/RpaQ2h/1/看到在该示例中,它似乎工作正常,因此我继续了Java中的实现:

final List<String> lines = new ArrayList<>();
final Matcher matcher = NEW_LINE_ACTION.matcher(message);

String rest = message;
int start = 0;
while (matcher.find()) {
    if (matcher.group("action") != null) continue;

    final String before = message.substring(start,matcher.start());
    if (!before.isEmpty()) lines.add(before.trim());

    start = matcher.end();
    rest = message.substring(start);
}

if (!rest.isEmpty()) lines.add(rest.trim());

return lines;

如果它们位于上面显示的模式之内,则应忽略任何\n,但是它从未与“ action”组匹配,似乎当将其添加到Java并且出现\n时,它永远不会匹配它。我对为什么有些困惑,因为它在regex101上可以正常工作。

解决方法

您无需检查组是否为action,而只需对组$1(第一个捕获组)使用正则表达式替换。

我也将您的正则表达式更改为(?<action>\[[^\]]*]\([^)]*\))|(?<break>\\n),因为[^\]]*不会回溯(.*?会回溯并导致更多步骤)。我对[^)]*做过同样的事情。

See code working here

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {

        final String regex = "(?<action>\\[[^\\]]*\\]\\([^)]*\\))|(?<break>\\\\n)";
        final String string = "message\\n [testing test](hover: actions!\\nnew line!) more\\nmessage";

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        final String result = matcher.replaceAll("$1");

        System.out.println(result);

    }

}