我想替换这个字符串:
- http://fitness.com/gorilla-bumpers
- http://www.fitness.com/gorilla-bumpers
,表达式为"产品:gorilla-bumpers"。
我有以下代码:
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);
如何在Java中再添加一个替代品? 将提供几种变体。谢谢
答案 0 :(得分:3)
就像这样:
String product = url.replace( "http://fitness.com/", "Product: " ).replace( "http://www.fitness.com/", "Product: " );
此外,您可以尝试正则表达式,因为.replaceAll
函数需要正则表达式
String product = url.replaceAll( "http:.*\/", "Product: " );
请注意,我不是正则表达式的专家,你应该创建自己的。这个替换每个http://BLABLA/字符串
答案 1 :(得分:1)
执行以下操作:
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);
答案 2 :(得分:0)
试试这个 -
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);