简体   繁体   中英

Remove string in between two characters

I got a problem trying to remove words from a string file, eg:

    String text = "data['danger.high'] && data['$safe.low'] || data['go.now']";

What I want to do its remove from the string everything that its between first single quote and '.' , the result I want its the following:

    result = "data[high] && data[low] || data[now]";

this would be the result I need.

So far what I got is

    String text = "data['danger.high'] && data['$safe.low'] || data['go.now']";
    text = text.replaceAll("\\'(.*?)\\.", "");

But this gives me

    result = "data[highlownow']"

What am I doing wrong?

UPDATE

Thanks for your answers, now my follow up question its lets say i have

    String text = "data['danger.high'] && (data['$safe.low'] || data['go.now'] == 'yes')";

I want the following result:

    result = "data[high] && (data[low] || data[now] == 'yes')"; 

Keeping the single quotes on this case the "yes".

You can do something like this:

text = text.replaceAll("\\'([$a-zA-Z]+)\\.", "'").replaceAll("'", "");

text.replaceAll("\\\\'([$a-zA-Z]+)\\\\.", "'") Will gove you:

 data['high'] && data['low'] || data['now']

and .replaceAll("'", ""); will give you the desired result (without the ' ).

data[high] && data[low] || data[now]

Your regex should be tweaked a little. Look for $ characters and [a-zA-Z] . I assume you want to retain the single quotes. Let me know if that is not needed. You can use replaceAll() on the string again to remove the single quotes too.

        String text = "data['danger.high'] && data['$safe.low'] || data['go.now']";
        text = text.replaceAll("\\'([$a-zA-Z]+)\\.", "'");
        System.out.println(text);

Output

data['high'] && data['low'] || data['now']

your expression is removing the characters that start from second single quote thats why you are geiinng this result You should prevent the replaceAll for character starting with ']

Use text = text.replaceAll("\\'([$a-zA-Z]+)\\.", "'");

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