如何在多行上匹配正则表达式 [英] How to match regex over multiple lines
问题描述
我有一个文本正文,我正在尝试在其中找到一个字符序列。 String.contains()
将无效,因此我尝试使用 String.matches
方法和正则表达式。我现在的正则表达式不起作用。以下是我的尝试:
I have a body of text and I am trying to find a character sequence within it. String.contains()
will not work so Im trying to use String.matches
method and a regular expression. My current regex isn't working. Here are my attempts:
"1stline\r\n2ndline".matches("(?im)^1stline$");
// returns false; I expect true
"1stline\r\n2ndline".matches("(?im)^1stline$")
// returns false
"1stline\r\n2ndline\r\n3rdline".matches("(?im)^2ndline$")
"1stline\n2ndline\n3rdline".matches("(?im)^2ndline$")
"1stline\n2ndline\n3rdline".matches("(?id)^2ndline$")
我应如何格式化我的正则表达式以使其返回true?
How should i format my regex so that it returns true?
推荐答案
您需要使用 s
标志(不是 m
标志)。
You need to use the s
flag (not the m
flag).
它被称为 DOTALL
选项。
It's called the DOTALL
option.
这对我有用:
String input = "1stline\n2ndLINE\n3rdline";
boolean b = input.matches("(?is).*2ndline.*");
我发现它这里。
注意你必须在正则表达式之前和之后使用。*
使用 String.matches()
。
Note you must use .*
before and after the regex if you want to use String.matches()
.
那是因为 String.matches()
尝试将整个字符串与模式匹配。
That's because String.matches()
attempts to match the entire string with the pattern.
(。 *
在正则表达式中使用时表示零个或多个字符)
另一种方法,此处:
String input = "1stline\n2ndLINE\n3rdline";
Pattern p = Pattern.compile("(?i)2ndline", Pattern.DOTALL);
Matcher m = p.matcher(input);
boolean b = m.find();
print("match found: " + b);
我通过Google搜索找到了 java regex multiline
并点击第一个结果。
I found it by googling "java regex multiline"
and clicking the first result.
(几乎就好像那个答案是为你而写的...... )
关于模式和正则表达式的信息很多此处。
There's a ton of info about patterns and regexes here.
如果您想匹配仅 第二行
出现在行的开头,执行此操作:
If you want to match only if 2ndline
appears at the beginning of a line, do this:
boolean b = input.matches("(?is).*\\n2ndline.*");
或者这个:
Pattern p = Pattern.compile("(?i)\\n2ndline", Pattern.DOTALL);
这篇关于如何在多行上匹配正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!