Kamil W
Kamil W

Reputation: 2366

Replace all occurrences matching given patterns

Having following string:

String value = "/cds/horse/schema1.0.0/day=12321/provider=samsung/run_key=32ee/group_key=222/end_date=2020-04-20/run_key_default=32sas1/somethingElse=else"

In need to replace values of run_key and run_key_default with %, for example, for above string result output will be the:

"/cds/horse/schema1.0.0/day=12321/provider=samsung/run_key=%/group_key=222/end_date=2020-04-20/run_key_default=%/somethingElse=else"

I would like to avoid mistakenly modifying other values, so in my opinion the best solution for it is combining replaceAll method with regex

String output = value.replaceAll("\run_key=[*]\", "%").replaceAll("\run_key_default=[*]\", "%")

I'm not sure how should I construct regex for it?

Feel free to post if you know better solution for it, than this one which I provided.

Upvotes: 1

Views: 91

Answers (2)

Amit Kumar Lal
Amit Kumar Lal

Reputation: 5789

public static void main(String[] args) {
        final String regex = "(run_key_default|run_key)=\\w*"; //regex
        final String string = "/cds/horse/schema1.0.0/day=12321/provider=samsung/run_key=32ee/group_key=222/end_date=2020-04-20/run_key_default=32sas1/somethingElse=else";
        final String subst = "$1=%"; //group1 as it is while remaining part with % 

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        final String result = matcher.replaceAll(subst);

        System.out.println("Substitution result: " + result);
    }

output

Substitution result:

/cds/horse/schema1.0.0/day=12321/provider=samsung/run_key=%/group_key=222/end_date=2020-04-20/run_key_default=%/somethingElse=else

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You may use this regex for search:

(/run_key(?:_default)?=)[^/]*

and for replacement use:

"$1%"

RegEx Demo

Java Code:

String output = value.replaceAll("(/run_key(?:_default)?=)[^/]*", "$1%");

RegEx Details:

  • (: Start capture group #1

    • /run_key: Match literal text /run_key
    • (?:_default)?: Match _default optionally
    • =: Match a literal =
  • ): End capture group #1

  • [^/]*: Match 0 or more of any characters that is not /

  • "$1%" is replacement that puts our 1st capture group back followed by a literal %

Upvotes: 4

Related Questions