简体   繁体   English

如何使用java Regex匹配两个字符串

[英]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?如何使用 Java 正则表达式匹配这两个字符串以使其返回 true? Basically {ID} can contain anything.基本上{ID}可以包含任何内容。 Java regex should match abc/{anything here}/plan/{anything here}/planID Java 正则表达式应该匹配abc/{anything here}/plan/{anything here}/planID

If your "{anything here}" includes nothing , you can use .* .如果您的“{anything here}”不包含任何内容,则可以使用.* . matches any letter, and * means that match the string with any length with the letter before, including 0 length.匹配任意字母, *表示匹配任意长度的字符串与前面的字母,包括0长度。 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.如果 {anything here} 应至少包含一个字母,则可以使用+代替* ,这意味着几乎相同,但应至少匹配一个字母。

My suggestion: abc/.+/plan/.+/planID我的建议: abc/.+/plan/.+/planID

If {ID} can contain anything I assume it can also be empty.如果 {ID} 可以包含任何内容,我认为它也可以为空。 So this regex should work :所以这个正则表达式应该可以工作:

str.matches("^abc.*plan.*planID$");
  • ^abc at the beginning ^abc 开头
  • .* Zero or more of any Character .* 零个或多个任何字符
  • planID$ at the end计划ID$在最后

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.具体来说,我使用正则表达式,因为您想使用 java 正则表达式进行匹配。

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:如果行始终以 'abc' 开头并以 'planid' 结尾,则以下方式将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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