简体   繁体   中英

How to use regular expressions to extract specific substrings and then build into a new string

I need the result String as (Relationship IN (11,12,1) AND (Item=79)). I have extracted the numbers 11,12 and 1 by the following code:

String str = "(( Relationship=11 ) AND ( Relationship=12 ) AND (Item=79) AND ( Relationship=1 ))";
String regex = "Relationship=(\\d+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);

List<String> list = new ArrayList<>();
while (matcher.find()) { 
    list.add(matcher.group(1));
    //System.out.println(matcher.group(1));
}
System.out.println(list.toString());

But how do I replace all the Relationship = with Relationship IN () ?

This code builds on what you already had, you were very close. It has been tested and as asked it gives you the extracted string " (Relationship IN (11,12,1) AND" in the new String relationshipnumber. There was no need for the List. You can extend the technique in the code to extract the item component of the string.

String str = "(( Relationship=11 ) AND ( Relationship=12 ) AND (Item=79) AND ( Relationship=1 ))";
            String regex = "Relationship=(\\d+)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);


            String relationshipnumber ="(";
            int i =0;
            while (matcher.find()) { 

                if (i==0){

                    relationshipnumber=relationshipnumber+matcher.group(1);
                }else{

                relationshipnumber=relationshipnumber+","+matcher.group(1);

                }
                i++;
            }
            relationshipnumber="(Relationship IN "+relationshipnumber+ ") AND";

how do I replace all the Relationship = with Relationship IN ()?

To do that you can just use String::replaceAll like this :

String str = "(( Relationship=11 ) AND ( Relationship=12 ) AND "
        + "(Item=79) AND ( Relationship=1 ))";

str = str.replaceAll("Relationship\\s*=", "Relationship IN ()");
System.out.println(str);

Output

(( Relationship IN ()11 ) AND ( Relationship IN ()12 ) AND (Item=79) AND ( Relationship IN ()1 ))

In case you want to put the inter part between () you can use :

str = str.replaceAll("Relationship\\s*=\\s*(\\d+)", "Relationship IN ($1)");

Output

(( Relationship IN (11) ) AND ( Relationship IN (12) ) AND (Item=79) AND ( Relationship IN (1) ))

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