1

I wanted to extract test 1 and this.test2 I did below and later processed the right hand side

 string1:test1 = {{this.test2}}

 String[] parts = string1.split("=");

I'm planning to extract/print id1 and id2, product_application,product1,this.product2 from above String.How can I split the string and extract them :

Test1:

id1 IN (SELECT id2 FROM product_application WHERE product1 = {{this.product2}})

Test2:

id3 IN (SELECT id4 FROM location WHERE region1 = {{this.region2}}

I want to extract or print like below.

Output for string 1:

id1, id2, product_application, product1, product2

Output for string 2:

id3, id4, location, region1, region2
2
  • Its more of url parsing I am trying to parse sql like string Commented Apr 19, 2017 at 18:23
  • Sorry your question is confusing to me. What string(s) do you have and what results do you want to get? Commented Apr 19, 2017 at 18:25

1 Answer 1

1

Here is a regex you can use it :

String str = 
       "id1 IN (SELECT id2 FROM product_application WHERE product1 = {{this.product2}})";

String regex = "(id\\d+)|(product_\\w+)|(product\\d+)";
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(str);
List<String> list = new ArrayList<>();
while (mat.find()) {
    list.add(mat.group());
}
System.out.println(list);

Output

[id1, id2, product_application, product1, product2]

EDIT

Your string is a little compecated, so i don't know if that help you or not, it work fine with the two examples in your question :

String[] spl = str.replaceAll("IN|SELECT|FROM|WHERE|(this\\.)|[(){}=,]|(\\s{2,})", " ").
        replaceAll("\\s+", " ").split("\\s");

The idea is :

  1. replace every thing IN or SELECT or FROM or WHERE or this. or [(){}=,] with a space.
  2. replace multiple Strings with one space 3.split the result with space, and you will get only your result.
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks but id1, id2, product_application, product1, product2 are variable I can get a different string it can be id3,id4,product_application_region,product3,product4
mmm, you had to make this in the first time @javascriptlearner ok i will check what i can do
its ok @javascriptlearner the name of idxxx are all like this format, or you can find for example a diffirent name?
@javascriptlearner can you please answer my question i'm trying to help you here :)
Thanks. It can be anything does not follow idxxx format.It can be like " test1 IN (SELECT test2...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.