seesee
seesee

Reputation: 1155

Extract data using REGEX

May I know how to extract the following data using REGEX?

1) textA;textB;textC;textD

Extract "textA;textB;textC" aka parent of textD

2) textA;textB;textC;textD AB(numberA)

Extract "textA;textB;textC;textD" aka parent of AB(numberA)

3) textA;textB;textC;textD AB(numberA) Extract "numberA" for comparison

currently implementation, i use java string function, which make it un-configurable. I suspect the user didn't give me the actual data and I need to change the function again in the near future. I hope to use regex to make the function configurable.

Upvotes: 0

Views: 269

Answers (2)

navins
navins

Reputation: 3469

can simply use this?

String[] arr = "textA;textB;textC;textD AB".spilt("[; ]");

Upvotes: 0

popfalushi
popfalushi

Reputation: 1362

  1. (.*);[a-zA-Z]+ - $1
  2. (.*) .* - $1
  3. .* .*\((.*)\) - $1
    How to use regexes and groups: http://www.javamex.com/tutorials/regular_expressions/capturing_groups.shtml
    Example:

    String s = "textA;textB;textC;textD";
    Pattern pt = Pattern.compile("(.*);[a-zA-Z]+");
    Matcher mt = pt.matcher(s);
    if(mt.matches())
        System.out.println(mt.group(1));
    

That prints: textA;textB;textC.
UPD: Because the pattern is not known, answer like 1)textA;textB;textC;(textD) is also true. When asking such questions, it is better to write pattern, even if you don't know regexes you can use words only.
UPD: thx for correction

Upvotes: 3

Related Questions