简体   繁体   English

Java ^正则表达式与字符串中的新行不匹配

[英]Java ^ regex does not match new line in string

this is my String 这是我的弦

REGISTER sip:192.168.178.1 SIP/2.0
Call-ID: bla@192.168.178.60
CSeq: 1441 REGISTER
From: "620" <sip:620@192.168.178.20>;tag=bla
To: "620" <sip:620@192.168.178.20>
Via: SIP/2.0UDP 192.168.178.60:59488;branch=bla;rport
Max-Forwards: 70
User-Agent: bla
Contact: *
Expires: 0
Content-Length: 0

So this string has several newlines. 因此,该字符串具有多个换行符。 My Regex is in this form: 我的正则表达式是这样的:

sipRequest = sipRequest.replaceFirst("(From: \")(.*)(\" <sip:)(.*)@(.*)>", "$1$2$3$4@" + sipServer + ">");

This Regex matches, but not the following one: 此正则表达式匹配,但不匹配以下一个:

sipRequest = sipRequest.replaceFirst("(^From: \")(.*)(\" <sip:)(.*)@(.*)>", "$1$2$3$4@" + sipServer + ">");

Note: Only difference is the "^" sign before "From". 注意:唯一的区别是“发件人”之前的“ ^”符号。 So why does this expression not match? 那么为什么这个表达式不匹配? It starts at a new line, so it should match. 它从新行开始,因此应该匹配。

Thanks for help. 感谢帮助。

Quoting the JavaDoc of Pattern : 引用Pattern的JavaDoc:

By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. 默认情况下,正则表达式^和$忽略行终止符,并且仅在整个输入序列的开头和结尾分别匹配。 If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. 如果激活了MULTILINE模式,则^在输入的开头和任何行终止符之后匹配,除了输入的末尾。 When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence. 在多行模式下,$匹配行终止符或输入序列末尾。

So you need to set the multiline flag, because the default meaning of ^ is beginning of string , not beginning of line. 因此,您需要设置多行标志,因为^的默认含义是string的开头,而不是line的开头。

The operation ^ works only if you are using Pattern.MULTILINE . ^操作仅在使用Pattern.MULTILINE Since string.replaceAll() creates patterns without options you have to create pattern yourself, than create matcher and use replacing facilities of matcher. 由于string.replaceAll()创建的模式没有选项,因此您必须自己创建模式,而不是创建匹配器并使用匹配器的替换功能。

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

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