4

I want to replace this strings: - http://fitness.com/gorilla-bumpers - http://www.fitness.com/gorilla-bumpers with the expression "Product: gorilla-bumpers".

I have the following code:

final String url = eElement.getElementsByTagName("url").item(0).getTextContent();
final String qty = eElement.getElementsByTagName("quantity").item(0).getTextContent();
//I 've got "url" and "qty" values from Xml after parsing it

String product = url.replace("http://fitness.com/", "Product: ");           
System.out.println(product + " was added to the cart with Qty = " + qty);

How can I add one more replacement in Java? Will be appreciate for several variants providing. Thank you

2
  • how about: by writing a second call to the replace method? Commented Feb 17, 2016 at 8:47
  • 1
    How about url.replace("http://fitness.com/", "Product: ").replace("","").replace.... Commented Feb 17, 2016 at 8:48

3 Answers 3

3

Just do it like:

String product = url.replace( "http://fitness.com/", "Product: " ).replace( "http://www.fitness.com/", "Product: " );

Also you can try regexes since .replaceAll function takes regex

String product = url.replaceAll( "http:.*\/", "Product: " );

Note that I'm not an expert on regexes, you should create your own. This one replaces every http://BLABLA/ strings

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

1 Comment

I've added another thing for you, you can try it as well
1

Do the following:

final String url = eElement.getElementsByTagName("url").item(0).getTextContent();
final String qty = eElement.getElementsByTagName("quantity").item(0).getTextContent();

String product = url.replace("http://fitness.com/", "Product: ")
                .replace("http://www.fitness.com/", "Product: ");
        System.out.println(product + " was added to the cart with Qty = " + qty);

1 Comment

Thank you. Can you Suggest any other variants of implementation?
0

Try this-

final String url = eElement.getElementsByTagName("url").item(0).getTextContent();
final String qty = eElement.getElementsByTagName("quantity").item(0).getTextContent();

String product = url.replaceAll("http://fitness.com/", "Product: ").replaceAll("http://www.fitness.com/", "Product: ");

System.out.println(product + " was added to the cart with Qty = " + qty);

2 Comments

but don't you think, your example will only replace this: http://fitness.com/? But not this: http://www.fitness.com/ And I need to replace both
@EvgEvg I have updated my answer. I am sorry, I didn't read the question correctly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.