简体   繁体   English

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

[英]How to match regex pattern on single line only?

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”匹配。

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

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 yo with word boundary and cut me: are matched in the same line. yo\\b[^\\n]*cut me:是先行模式,确保带有单词边界的yocut me:匹配在同一行。

Remove the s or DOTALL flag and change your regex to the following: 删除sDOTALL标志并将正则表达式更改为以下内容:

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

With the DOTALL flag enabled . 启用DOTALL标志. will match newline characters, so your match can span multiple lines including lines before yo or between yo and cut me . 将匹配换行符,因此您的匹配可以跨越多行,包括yo之前的行或yo之间的行和cut me By removing this flag you can ensure that you only match the line with both yo and 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. 通过删除此标志,您可以确保只匹配yocut 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. 编辑:请注意,这与其他答案略有不同,这将匹配您要删除的字符串部分,因此您可以用空字符串替换此部分以将其删除。

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

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