简体   繁体   English

使用条件按新行拆分字符串

[英]Splitting string by new line with a condition

I am trying to split a String by \n only when it's not in my "action block".只有当字符串不在我的“操作块”中时,我才尝试将字符串拆分为\n
Here is an example of a text message\n [testing](hover: actions!\nnew line!) more\nmessage I want to split when ever the \n is not inside the [](this \n should be ignored) , I made a regex for it that you can see here https://regex101.com/r/RpaQ2h/1/ in the example it seems like it's working correctly so I followed up with an implementation in Java:这是一个文本message\n [testing](hover: actions!\nnew line!) more\nmessage I want to split when ever the \n is not inside the [](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;

This should ignore any \n if they are inside the pattern showed above, however it never matches the "action" group, seems like when it is added to java and a \n is present it never matches it.这应该忽略任何\n如果它们在上面显示的模式内,但是它永远不会匹配“动作”组,就像当它被添加到 java 并且存在\n时它永远不会匹配它。 I am a bit confused as to why, since it worked perfectly on the regex101.我对为什么有点困惑,因为它在 regex101 上运行良好。

Instead of checking whether the group is action , you can simply use regex replacement with the group $1 (the first capture group).无需检查组是否为action ,您可以简单地使用组$1 (第一个捕获组)的正则表达式替换。

I also changed your regex to (?<action>\[[^\]]*]\([^)]*\))|(?<break>\\n) as [^\]]* doesn't backtrack ( .*? backtracks and causes more steps).我还将您的正则表达式更改为(?<action>\[[^\]]*]\([^)]*\))|(?<break>\\n)因为[^\]]*没有回溯( .*?回溯并导致更多步骤)。 I did the same with [^)]* .我对[^)]*做了同样的事情。

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);

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM