1

Let's say I have a string, different version of the input string:

a) Name='book' Number='345' Version='12' Author='name1'
b) Name='book' Version='12' Author='name1' Number='345'

I need to remove Version='xx' and Number='xx'from this input string. Values of this parameters can be always changed.

What is the best way to do it? I tried regex, something like:

String input = input.substring(0, input.indexOf("Number")) + "" + input.substring(input.indexOf("Version"));

But that would work only for this case:

a) Name='book' Number='345' Version='12' Author='name1'

But not for this:

b) Name='book' Version='12' Author='name1' Number='345'

So how to make a general approach?

2 Answers 2

5

You can use a regular expression to replace:

"Name='book' Number='345' Version='12' Author='name1'"
    .replaceAll("( Number| Version)='\\d+'", "")

That returns Name='book' Author='name1'

replaceAll("( Number| Version)='\\d+'", "") finds Number OR Version followed by a number in single quotes, and replaces it with a blank string.

As suggested by Aaron's comment below, if the order of key/value pairs can change, then a different regex may be better:

s.replaceAll("(?:^| )(?:Number|Version)='\\d+'", "").trim()

This will match the keys whether they're preceded by a space or are at the beginning of the line.

Sign up to request clarification or add additional context in comments.

6 Comments

Aren't you missing a group around the Number| Version alternation? Name='book'='345' doesn't look right to me
Another problem : since the order of the attributes seems variable, you should match them preceded by either space or the start of the string
@Aaron Makes perfect sense. I just have to find an explanation for why it works without the group.
It doesn't, look at what you wrote it returned : Name='book'='345' likely isn't what OP wants ;)
@Aaron 100% Thanks. I'm possibly sleep-typing. You're right
|
0

You can achieve what you want to do with regex using replaceAll method as below :

    String input = "Name='book' Number='345' Version='12' Author='name1'";
    String input2 = "Name='book' Version='345' Number='12' Author='name1'";

    input = input.replaceAll("(Number|Version)='\\d+'", "");
    input2 = input2.replaceAll("(Number|Version)='\\d+'", "");

    System.out.println(input);
    System.out.println(input2);

output is :

Name='book'   Author='name1'
Name='book'   Author='name1'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.