java - 正则表达式替换字符串中的所有\n,但不替换 [code] [/code] 标记中的那些

标签 java regex

我需要帮助替换字符串中
的所有\n(新行)字符,但不是 [code][/code] 标签内的那些\n。 我的脑子在燃烧,我无法自己解决这个问题:(

例子:

test test test
test test test
test
test

[code]some
test
code
[/code]

more text

应该是:

test test test<br />
test test test<br />
test<br />
test<br />
<br />
[code]some
test
code
[/code]<br />
<br />
more text<br />

感谢您的宝贵时间。 最好的问候。

最佳答案

我建议使用(简单的)解析器,而不是正则表达式。像这样的东西(糟糕的伪代码):

stack elementStack;

foreach(char in string) {
    if(string-from-char == "[code]") {
        elementStack.push("code");
        string-from-char = "";
    }

    if(string-from-char == "[/code]") {
        elementStack.popTo("code");
        string-from-char = "";
    }

    if(char == "\n" && !elementStack.contains("code")) {
        char = "<br/>\n";
    }
}

关于java - 正则表达式替换字符串中的所有\n,但不替换 [code] [/code] 标记中的那些,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/328387/

相关文章:

java - 设计模式: many objects of same type with multiple objects of other type

java - 在同一个响应中设置多个 cookie

regex - 正则表达式密码验证

python - Lookahead 捕获不需要的字符

javascript - 用于将引用语法转换为 HTML 的正则表达式

java - 为什么Maven不在我的〜/.m2文件夹中寻找?

java - 扩展 JPA 实体以添加属性和逻辑

java - 当用户点击 "Delete data"Android 时如何执行我的应用程序方法

jquery - 按多个字符串或冒号分割 (jQuery)

regex - 如何用空格分隔千位