Java Replace String with two (or more) expressions

I want to replace these lines: - http://fitness.com/gorilla-bumpers- http://www.fitness.com/gorilla-bumperswith 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 to add another replacement in Java? Several delivery options will be appreciated. thank you

+4
source share
3 answers

Just do it:

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

You can also try regular expressions, as the function .replaceAllaccepts regex

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

Please note that I am not a regular expression specialist; you must create your own. This replaces each line http: // BLABLA /

+3
source

:

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

-

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);
0

Source: https://habr.com/ru/post/1629127/


All Articles