Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get substring in a string with multiple occurring string

Tags:

java

I have a string something like

(D@01)5(D@02)14100319530033M(D@03)1336009-A-A(D@04)141002A171(D@05)1(D@06)

Now i want to get substring between (D@01)5(D@02)

If i have something like

(D@01)5(D@02)

i can get detail with

    quantity         = content.substring(content.indexOf("(D@01)") + 6, content.indexOf("(D@02)"));

But somethings D@02 can be different like @05, Now how can i use simple (D@ to get string in between. there are multiple repetitions of (D@

Basically this is what i want to do

content.substring(content.indexOf("(D@01)") + 6, content.nextOccurringIndexOf("(D@"));
like image 376
Muhammad Umar Avatar asked Apr 21 '26 03:04

Muhammad Umar


1 Answers

I suppose you can do

int fromIndex = content.indexOf("(D@01)") + 6;
int toIndex = content.indexOf("(D@", fromIndex);    // next occurring

if (fromIndex != -1 && toIndex != -1)
    str = content.substring(fromIndex, toIndex);

Output

5

See http://ideone.com/RrUtBy demo.

like image 104
Shreevardhan Avatar answered Apr 22 '26 16:04

Shreevardhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!