How to match “any character” in regular expression?

前端 未结 11 673
忘了有多久
忘了有多久 2020-11-27 09:23

The following should be matched:

AAA123
ABCDEFGH123
XXXX123

can I do: \".*123\" ?

11条回答
  •  时光说笑
    2020-11-27 10:01

    .* and .+ are for any chars except for new lines.

    Double Escaping

    Just in case, you would wanted to include new lines, the following expressions might also work for those languages that double escaping is required such as Java or C++:

    [\\s\\S]*
    [\\d\\D]*
    [\\w\\W]*
    

    for zero or more times, or

    [\\s\\S]+
    [\\d\\D]+
    [\\w\\W]+
    

    for one or more times.

    Single Escaping:

    Double escaping is not required for some languages such as, C#, PHP, Ruby, PERL, Python, JavaScript:

    [\s\S]*
    [\d\D]*
    [\w\W]*
    [\s\S]+
    [\d\D]+
    [\w\W]+
    

    Test

    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));
            }
        }
    }
    

    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
    

    If you wish to explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


    RegEx Circuit

    jex.im visualizes regular expressions:

提交回复
热议问题