Java 如何仅在单行上匹配正则表达式模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22490149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:02:52  来源:igfitidea点击:

How to match regex pattern on single line only?

javaregex

提问by genxgeek

I have the following regex and sample input:

我有以下正则表达式和示例输入:

http://regex101.com/r/xK9dE3

http://regex101.com/r/xK9dE3

As you can see it matching the first "yo". I only want the pattern to match on the same line (the second "yo") pattern with "cut me".

如您所见,它匹配第一个“yo”。我只希望模式与“cut me”在同一行(第二个“yo”)模式上匹配。

How can I make sure that the regex match is only on the same line?

如何确保正则表达式匹配仅在同一行?

Output:

输出:

Hi

Expected Output (this is what I really want):

预期输出(这是我真正想要的):

Hi

yo keep this here

Keep this here

采纳答案by Andrew Clark

Remove the sor DOTALLflag and change your regex to the following:

删除sorDOTALL标志并将您的正则表达式更改为以下内容:

^.*?((\yo\b.*?(cut me:)[\s\S]*))

With the DOTALLflag enabled .will match newline characters, so your match can span multiple lines including lines before yoor between yoand cut me. By removing this flag you can ensure that you only match the line with both yoand cut me, and then change the .*at the end to [\s\S]*which will match any character including newlines so that you can match to the end of the string.

DOTALL启用该标志.将匹配换行符,因此您的匹配可以跨越多行,包括和之前yo或之间的行。移除此标志,你可以确保你只匹配与两个行和,然后更改在结束时将匹配包括换行,这样就可以匹配到字符串的结尾任何字符。yocut meyocut me.*[\s\S]*

http://regex101.com/r/sX2kL0

http://regex101.com/r/sX2kL0

edit:Note that this takes a slightly different approach than the other answer, this will match the portion of the string that you want deleted so you can replace this portion with an empty string to remove it.

编辑:请注意,这与其他答案采用的方法略有不同,这将匹配您要删除的字符串部分,因此您可以用空字符串替换此部分以将其删除。

回答by anubhava

You can use this regex with s(DOTALL) regex flag:

您可以将此正则表达式与s(DOTALL) 正则表达式标志一起使用:

^.*?(?=yo\b[^\n]*cut me:)

Online Demo: http://regex101.com/r/oV3eP7

在线演示:http: //regex101.com/r/oV3eP7

yo\b[^\n]*cut me:is lookahead pattern that makes sure that yowith word boundary and cut me:are matched in the same line.

yo\b[^\n]*cut me:是前瞻模式,确保yo与单词边界并cut me:在同一行中匹配。