简体   繁体   中英

String comparision of patterns in java

Let's say I have a string pattern as

/users/{id}

And Urls I am getting could be

/users/1  
/users/abc123
/users/etc

I mean dynamic so I have 2 variables.

String dynamicPathPattern = "/users/{id}";
String dynamicPath = "/users/1";

/*
 Something that will convert string pattern to regular expression. And compare it.
*/

Now my question is how to compare this?
I think it's is possible with regular expression. Can anyone guide please how should I start?
Is there anything readily available that I can use like String.equals() ?

The pattern you are looking for would be \\{[^\\{]+\\} . It searches for anything in curly brackets.

An idea would be converting your source pattern to a wrapper object, which stores the compiled pattern (escape everything except the variables) plus the name of each variable.


EDIT: For your case, an example would look like this:

First, create a class Range containg two int for start and end . Then determine all variable ranges from yourPatternString :

Pattern variablePattern = Pattern.compile("\\{[^\\{]+\\}");
Matcher variableMatcher = variablePattern.matcher(yourPatternString);
List<Range> variableRanges = new ArrayList<>();

while(variableMatcher.find()) {
    variableRanges.add(new Range(variableMatcher.start(), variableMatcher.end()));
}

Now, using these ranges, you can create a new regular expression from your pattern, by replacing each range with for example [a-zA-Z]+ . You can then simply compile a pattern and create a matcher on your input string as above.

After trying a lot with regx. This is the code which satisfies all the needs. I hope so it will help others as well.

    String[] dynamicPathArray = dynamiPathPattern.split("/");
    String generatedPattern = "";
    for (int j = 1; j < dynamicPathArray.length; j++) {
        if (dynamicPathArray[j].contains("{")) {
            dynamicPathArray[j] = "[\\w\\s.-]+";
        } else {
            dynamicPathArray[j] = "\\b" + dynamicPathArray[j] + "\\b";
        }
        generatedPattern = generatedPattern + "/" + dynamicPathArray[j];
    }
    Pattern variablePattern = Pattern.compile(generatedPattern);
    Matcher variableMatcher = variablePattern.matcher(dynamicPath);
    if (variableMatcher.find()) {
        //Do whatever needed
    }

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