简体   繁体   中英

Replace substring from a string

I have this string

String str=lookup('PRODUCT','LKP1','LKP_TAB1.ID')||('A'='B')-lookup('PRODUCT','LKP2','LKP_TAB1.ID')||'CON.ID'

This is just one example, in practical situation the lookup expression may exist any where and any number of times in the string. Also the string may have several other '(' and ')'. I need to convert the string to

=lookup('PRODUCT','LKP1','LKP_TAB1.ID',123)||('A'='B')-lookup('PRODUCT','LKP2','LKP_TAB1.ID',123)||'CON.ID'

It means I need to replace the ')' with ',123)' when it comes with lookup. But if it is not adjuscent with lookup then I dont wanna replace it.

Can this thing be done in java??

Try:

str = str.replaceAll("(lookup\\([^)]*)\\)","$1,123)");

See it @ work

I think this is too much work and cleverness to be worth it.

I'd be lazy and have to final static instances, one String per case. Then I'd write an if test to decide which one to use.

Why do all that work every time? How many times will this operation be performed? If there are only two answers, spell them out. I think it'll be more readable and less load on the CPU.

Sure,

this can be done in any language, Java as well.

How about this :

Tokenize the string on ')'.

Then, if the token contains the word 'lookup', replace the last instance of ')' with '123)'.

I think that might work, it's ugly, but seems fine.

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