java - 结合两个java正则表达式

标签 java regex string replace replaceall

不得不第一次使用正则表达式,尽管我几乎达到了我的要求,但我似乎无法将其组合成一个语句。

我有一串单词,如果它前面没有点或前面没有点空格,我希望替换 \n

我可以运行这两个语句中的任何一个来获得所需的结果。但是,如果我一个接一个地运行它们或尝试将它们组合成一个正则表达式,它就不起作用。

//replaces \n if not preceded by dot space
xx = xx.replaceAll("(.+)(?<!\\. )\n", "$1 ");


//replaces \n if not preceded by dot
xx = xx.replaceAll("(.+)(?<!\\.)\n", "$1 "); 


//one of my attempts to combine into a single statement
xx = xx.replaceAll("(.+)(?<!\\. )\n|(?<!\\.)\n", "$1 ");

我正在尝试修复的字符串示例。

之前

This is some text which may\n
have a newline character to break the line\n
but I only want to remove it if it's not preceded with a full.\n
or it's not preceded with a full stop and a space. \n

之后

This is some text which may
have a newline character to break the line 
but I only want to remove it if it's not preceded with a full.\n
or it's not preceded with a full stop and a space. \n

我想我已经很接近了,但是作为正则表达式的新手,我读得越多就越困惑。

最佳答案

这比你想象的要容易:

String resultString = subjectString.replaceAll("(?<!\\. ?)\n", " ");

解释:

(?<!   # Assert that the previous characters are not...
 \.    # a dot
 [ ]?  # optionally followed by a space
)      # End of lookbehind
\n     # Match a newline character

所以你不需要首先匹配 (.+) ,只需要在之后用它自己替换它。顺便说一下,这是让你绊倒的原因:

(.+)(?<!\. )\n|(?<!\.)\n

在逻辑上被分组为

(.+)(?<!\. )\n   # Match this
|                # or
(?<!\.)\n        # this

因此 (.+) 仅在点后没有空格时匹配。

关于java - 结合两个java正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14318255/

相关文章:

java - 限制子类字段类型

java - JPA 插入和更新

java - 使用有限状态机解析文件

PHP 正则表达式字母数字受非字母数字限制

c# - 为什么我不能在公共(public)静态字符串上使用串联

java - 安卓工作室 : error: incompatible types: double cannot be converted to String

Java中,Parser只解析一次数据。需要解析为eof

ruby - 扫描方法没有按预期工作

Java 正则表达式 : make it find longest match?

c - C 中 char[] 和 char* 的区别