current position:Home>Java regular expression matching and common error handling

Java regular expression matching and common error handling

2022-01-26 23:55:27 tea-Sir

Java There is a way to match regular expressions , as follows :

Pattern.matches(regex,str)

among regex Rules for matching ,str For the string to be matched .

/** * @description: Regular expression matching lookup test  * @author: teasir * @create: 2021/12/16 **/
public class PatternTest {
    
    public static void main(String[] args) {
    
        List<String> lists=new ArrayList<>();
        lists.add("+862-13135825643");
        lists.add("[email protected]");
        // Define regular expression matching rules ,* Indicates that multiple strings can be matched 
        String regex=".*"+".+862-13135825642"+".*";
        System.out.println(regex);
        for (String str:lists){
    
            System.out.println(str);
           if(Pattern.matches(regex,str)){
    
               System.out.println(" The match is successful :"+str);
           }
        }
    }
}

 Output :
.*.+862-13135825642.*
+862-13135825642
 The match is successful +862-13135825642
1657245614@qq.com

Add above “.” It's to make "*"、"+" And other characters with special meaning in regular expressions .

Otherwise, the following error will be reported :

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

Query relevant data display ,+、*、|、\ Equal symbols have different meanings in regular expression .
Generally speaking, you only need to add "." that will do .

Reference article
https://blog.csdn.net/qq_33522040/article/details/86006960
https://www.nhooo.com/note/qa0ui8.html

copyright notice
author[tea-Sir],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262355252121.html

Random recommended