简体   繁体   中英

Convert this pattern to regex for Pattern.matches(..)

Some of my strings may contain a substring that looks like @[alph4Num3ric-alph4Num3ric] , where I will find the alpha numberic id and replace it with a corresponding text value mapped to the associated key in a map.

My first inclination was to check if my string.contains("@[") but I want to be more specific

so now I am looking at Pattern.matches( but am unsure of the regex and total expression

how would I regex for @[ ...... - .... ] in the Pattern.matches method, it must also account for dashes. So I'm not sure what needs to be escaped in this syntax or wildcarded, or more.

I am also not 100% sure if this is the best message. I want to get a boolean from Pattern.matches first, and then get the real value and modify the string with those values, which seems good enough, but I want to minimize computations.

Try using this:

/@[(a-zA-Z0-9-)+]/

I haven't given it a try but hope this would help. Also if it returns an error then add a backward slash between 9 and - eg /@[(a-zA-Z0-9-)+]/

Plese try this ,

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

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String expression = "String contains @[alph4Num3ric-alph4Num3ric] as substring";

        Pattern pattern = Pattern
                .compile("\\@\\[([a-zA-Z0-9]+)-([a-zA-Z0-9]+)\\]");
        Matcher matcher = pattern.matcher(expression);
        while (matcher.find()) {
            System.out.println("matched: "+matcher.group());
            System.out.println("group1: "+matcher.group(1));
            System.out.println("group2: "+matcher.group(2));
            System.out
                    .println("after replace "+expression.replace(matcher.group(1), "customkey"));
        }
    }

}

output :

matched: @[alph4Num3ric-alph4Num3ric]
group1: alph4Num3ric
group2: alph4Num3ric
after replace: String contains @[customkey-customkey] as substring

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