[英]How to use java regex to match a line
The raw data is:原始数据是:
auser1 home1b
auser2 home2b
auser3 home3b
I want to match a line, but it doesn't work using ^(.*?)$
我想匹配一行,但使用
^(.*?)$
不起作用
However, I can use a(.*?)b
to match user1 home1
.但是,我可以使用
a(.*?)b
来匹配user1 home1
。
How can I match auser1 home1b
如何匹配
auser1 home1b
By default, ^
and $
match the start- and end-of-input respectively.默认情况下,
^
和$
分别匹配输入的开始和结束。 You'll need to enable MULTI-LINE mode with (?m)
, which causes ^
and $
to match the start- and end-of-line:您需要使用
(?m)
启用多行模式,这会导致^
和$
匹配行的开始和结束:
(?m)^.*$
The demo:演示:
import java.util.regex.*;
public class Main {
public static void main(String[] args) throws Exception {
String text = "auser1 home1b\n" +
"auser2 home2b\n" +
"auser3 home3b";
Matcher m = Pattern.compile("(?m)^.*$").matcher(text);
while (m.find()) {
System.out.println("line = " + m.group());
}
}
}
produces the following output:产生以下 output:
line = auser1 home1b line = auser2 home2b line = auser3 home3b
The fact that ^.*$
didn't match anything is because the .
^.*$
不匹配任何内容的事实是因为.
by default doesn't match \r
and \n
.默认情况下不匹配
\r
和\n
。 If you enable DOT-ALL with (?s)
, causing the .
如果使用
(?s)
启用 DOT-ALL,则会导致.
to match those as well, you'll see the entire input string being matched:为了匹配这些,你会看到整个输入字符串被匹配:
(?s)^.*$
In this case, you mind as well drop the ^
and $
and simply look for the pattern .*
.在这种情况下,您也可以删除
^
和$
并简单地查找模式.*
。 Since .
由于
.
will not match \n
, you'll end up with the same matches when looking for (?m)^.*$
, as @Kobi rightfully mentioned in the comments.将不匹配
\n
,您在寻找(?m)^.*$
时会得到相同的匹配,正如@Kobi 在评论中正确提到的那样。
we can also use the flag MULTILINE
,我们也可以使用标志
MULTILINE
,
Matcher m = Pattern.compile("^.*$",Pattern.MULTILINE).matcher(text);
This will enable the multiline mode which will gave you the expected result.这将启用多行模式,这将为您提供预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.