This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
Question: How do I use regular expressions to match arbitrary characters?
I want to match the following characters
AAA123
ABCDEFGH123
XXXX123
Copy the code
Can I use this expression:.*123?
Answer a
.* and.+ represent all characters except blank lines.Copy the code
Double translation
Just in case, the following expressions can also be used in languages that require double translation, such as Java or C++ :
[\\s\\S]*
[\\d\\D]*
[\\w\\W]*
Copy the code
Zero or more occurrences
[\\s\\S]+
[\\d\\D]+
[\\w\\W]+
Copy the code
One or more occurrences
Single translation
Some languages do not require double translation, such as C#, PHP, Ruby, PERL, Python, JavaScript
[\s\S]*
[\d\D]*
[\w\W]*
[\s\S]+
[\d\D]+
[\w\W]+
Copy the code
The test method
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)); }}}Copy the code
The output
Full Match for Expression 1: AAA123
ABCDEFGH123
XXXX123
Full Match for Expression 2: AAA123
ABCDEFGH123
XXXX123
Full Match for Expression 3: AAA123
ABCDEFGH123
XXXX123
Copy the code
Answer two
Your answer is right
. = Any character except a blank line
\. = The actual dot character
.? =.{0,1} = matches any character except newline zero or once
.* =.{0,} = Matches any character other than newline zero or more times
.+ =.{1,} = Matches any character except newline one or more times
How do I match newlines
Pass the DOTALL flag when writing an expression
Pattern pattern = Pattern.compile(". * 123", Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
Copy the code
The article translated from Stack Overflow:stackoverflow.com/questions/2…