【问题标题】:Splitting string by new line with a condition使用条件按新行拆分字符串
【发布时间】:2020-08-20 17:03:01
【问题描述】:

我试图通过\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 上完美运行。

【问题讨论】:

  • 这是您要查找的内容:tio.run/…?
  • @ctwheels 是的!成功了!
  • 作为参考,regex101 有一个代码生成器。让您的生活更轻松 :) 我刚刚添加了 $1 的替换以确保您的字符串保持操作(而不是检查组是否已设置,然后使用代码逻辑进行操作)。更简单、更清洁,并且不太可能导致错误。
  • 我会记住的,非常感谢!
  • @hev1 可能是个好主意,因为它仍未得到答复,已完成 :)

标签: java regex newline


【解决方案1】:

您可以简单地使用组$1(第一个捕获组)进行正则表达式替换,而不是检查组是否为action

我还将您的正则表达式更改为(?&lt;action&gt;\[[^\]]*]\([^)]*\))|(?&lt;break&gt;\\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);

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多