Java正则表达式匹配无回车符,后跟换行符 [英] Java regular expression matching no carriage return followed by a linefeed

查看:79
本文介绍了Java正则表达式匹配无回车符,后跟换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过(^ \ r)\ n ,但这是行不通的.

I've tried (^\r)\n but this doesn't work.

您如何做到的?

(感谢您在类似Java的代码中使用(^ \\ r)\\ n )

(I appreciate that in Java-like code you need to use (^\\r)\\n)

谢谢

推荐答案

取决于您的要求:

  • [^ \ r] \ n -换行符,除换行符外,前面带有任何字符.这意味着在换行符之前必须有一个字符,并且两个符号将被匹配.
  • (?<!\ r)\ n -不带回车符的换行符.这意味着只有换行符号会被匹配,并且 \ r 仅会被测试是否存在(因为(?<!\ r)是一个负向后看,即是零宽度断言,该断言不占用任何文本,但是如果其中的模式恰好在字符串中的当前位置之前不存在,则返回true.
  • [^\r]\n - linefeed that is preceded with any character but a carriage return. This means there must be a character before the linefeed and two symbols will be matched.
  • (?<!\r)\n - linefeed that is not preceded with a carriage return. This means there only newline symbol will get matched and \r will only be tested for presence (as (?<!\r) is a negative lookbehind, a zero-width assertion that does not consume any text, but returns true if the pattern inside it is absent right before the current position in the string).

有关演示,请检查以下两个链接:

For a demo, please check these two links:

  • At regex101.com, (?<!\r)\n is matching as linebreaks are pure \n at the Web site
  • At regexstorm.net, the same pattern does not match anything as linebreaks are \r\n there.

这篇关于Java正则表达式匹配无回车符,后跟换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆