简体   繁体   English

如何使用正则表达式提取特定的子字符串,然后构建为新字符串

[英]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)). 我需要结果字符串为(Relationship IN(11,12,1)AND(Item = 79))。 I have extracted the numbers 11,12 and 1 by the following code: 我通过以下代码提取了数字11,12和1:

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 () ? 但是,如何用Relationship IN ()替换所有Relationship =

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关系编号中为您提供提取的字符串“(Relationship IN(11,12,1)AND”。不需要列表。您可以扩展代码中的技术以提取字符串的项目组成部分。

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 ()? 如何用Relationship IN()替换所有Relationship =?

To do that you can just use String::replaceAll like this : 为此,您可以像这样使用String :: replaceAll

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

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

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