如何使用java正则表达式来匹配一行 [英] How to use java regex to match a line
问题描述
原始数据是:
auser1 home1b
auser2 home2b
auser3 home3b
我想匹配一行,但使用 ^(。*? )$
I want to match a line, but it doesn't work using ^(.*?)$
但是,我可以使用 a(。*?)b
来匹配 user1 home1
。
However, I can use a(.*?)b
to match user1 home1
.
如何匹配 auser1 home1b
推荐答案
默认情况下, ^
和 $
分别匹配输入的开始和结束。您需要使用(?m)
启用MULTI-LINE模式,这会导致 ^
和 $
匹配开头和结尾:
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)^.*$
演示:
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());
}
}
}
产生以下输出:
line = auser1 home1b
line = auser2 home2b
line = auser3 home3b
编辑我
^。* $
与任何事情都不匹配的事实是因为。
默认情况下与 \ r
和 \ n $ c不匹配$ C>。如果你用
(?s)
启用DOT-ALL,导致。
也匹配那些,你会看到匹配的整个输入字符串:
EDIT I
The fact that ^.*$
didn't match anything is because the .
by default doesn't match \r
and \n
. If you enable DOT-ALL with (?s)
, causing the .
to match those as well, you'll see the entire input string being matched:
(?s)^.*$
编辑II
在这种情况下,你还要放弃 ^
和 $
,只需查找模式。*
。由于。
与 \ n
不匹配,因此在寻找<$ c时,您将获得相同的匹配$ c>(?m)^。* $ ,正如@Kobi在评论中正确提到的那样。
EDIT II
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.
这篇关于如何使用java正则表达式来匹配一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!