本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
提问:如何用正则表达式匹配任意字符?
我想匹配下面的字符
AAA123
ABCDEFGH123
XXXX123
复制代码
我可以使用这个表达式吗:.*123
?
回答一
.*和.+代表除空行以外的所有字符。
复制代码
双重转译
为了以防万一,下面的表达式也可以用于那些需要双重转译的语言,比如java
、C++
:
[\\s\\S]*
[\\d\\D]*
[\\w\\W]*
复制代码
出现0次或多次
[\\s\\S]+
[\\d\\D]+
[\\w\\W]+
复制代码
出现一次或多次
单转译
某些语言不需要双重转译,比如C#
、PHP
、Ruby
、PERL
、Python
、JavaScript
[\s\S]*
[\d\D]*
[\w\W]*
[\s\S]+
[\d\D]+
[\w\W]+
复制代码
测试方法
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex_1 = "[\\s\\S]*";
final String regex_2 = "[\\d\\D]*";
final String regex_3 = "[\\w\\W]*";
final String string = "AAA123\n\t"
+ "ABCDEFGH123\n\t"
+ "XXXX123\n\t";
final Pattern pattern_1 = Pattern.compile(regex_1);
final Pattern pattern_2 = Pattern.compile(regex_2);
final Pattern pattern_3 = Pattern.compile(regex_3);
final Matcher matcher_1 = pattern_1.matcher(string);
final Matcher matcher_2 = pattern_2.matcher(string);
final Matcher matcher_3 = pattern_3.matcher(string);
if (matcher_1.find()) {
System.out.println("Full Match for Expression 1: " + matcher_1.group(0));
}
if (matcher_2.find()) {
System.out.println("Full Match for Expression 2: " + matcher_2.group(0));
}
if (matcher_3.find()) {
System.out.println("Full Match for Expression 3: " + matcher_3.group(0));
}
}
}
复制代码
输出
Full Match for Expression 1: AAA123
ABCDEFGH123
XXXX123
Full Match for Expression 2: AAA123
ABCDEFGH123
XXXX123
Full Match for Expression 3: AAA123
ABCDEFGH123
XXXX123
复制代码
回答二
你的答案是对的
.
= 任何字符除了空行
\.
= 实际的点字符
.?
= .{0,1}
= 匹配除换行符以外的任何字符零次或一次
.*
= .{0,}
= 匹配除换行符以外的任何字符零次或多次
.+
= .{1,}
= 匹配除换行符以外的任何字符一次或多次
如何匹配换行符
在写表达式的时候传入DOTALL
标志
Pattern pattern = Pattern.compile(".*123", Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
复制代码
文章翻译自Stack Overflow:stackoverflow.com/questions/2…
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END