简体   繁体   中英

How to match two string using java Regex

String 1= abc/{ID}/plan/{ID}/planID
String 2=abc/1234/plan/456/planID

How can I match these two strings using Java regex so that it returns true? Basically {ID} can contain anything. Java regex should match abc/{anything here}/plan/{anything here}/planID

If your "{anything here}" includes nothing , you can use .* . . matches any letter, and * means that match the string with any length with the letter before, including 0 length. So .* means that "match the string with any length, composed with any letter". If {anything here} should include at least one letter, you can use + , instead of * , which means almost the same, but should match at least one letter.

My suggestion: abc/.+/plan/.+/planID

If {ID} can contain anything I assume it can also be empty. So this regex should work :

str.matches("^abc.*plan.*planID$");
  • ^abc at the beginning
  • .* Zero or more of any Character
  • planID$ at the end

I am just writing a small code, just check it and start making changes as per you requirement. This is working, check for your other test cases, if there is any issue please comment that test case. Specifically I am using regex, because you want to match using java regex.

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

class MatchUsingRejex 
{ 
    public static void main(String args[]) 
    { 
        // Create a pattern to be searched 
        Pattern pattern = Pattern.compile("abc/.+/plan/.+/planID"); 

        // checking, Is pattern match or not
        Matcher isMatch = pattern.matcher("abc/1234/plan/456/planID"); 

        if (isMatch.find()) 
            System.out.println("Yes");
        else
            System.out.println("No");
    } 
} 

If line always starts with 'abc' and ends with 'planid' then following way will work:

String s1 = "abc/{ID}/plan/{ID}/planID";
String s2 = "abc/1234/plan/456/planID";

String pattern = "(?i)abc(?:/\\S+)+planID$";

boolean b1 = s1.matches(pattern);
boolean b2 = s2.matches(pattern);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM