Java用两个(或更多)表达式替换字符串
我要替换此字符串: -Java用两个(或更多)表达式替换字符串,java,regex,replace,str-replace,Java,Regex,Replace,Str Replace,我要替换此字符串: -http://fitness.com/gorilla-bumpers-http://www.fitness.com/gorilla-bumpers带有“产品:gorilla保险杠”字样 我有以下代码: final String url = eElement.getElementsByTagName("url").item(0).getTextContent(); final String qty = eElement.getElementsByTagName("quanti
http://fitness.com/gorilla-bumpers
-http://www.fitness.com/gorilla-bumpers
带有“产品:gorilla保险杠”字样
我有以下代码:
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中再添加一个替换项?
如能提供多种型号,将不胜感激。谢谢你就这样做吧:
String product = url.replace( "http://fitness.com/", "Product: " ).replace( "http://www.fitness.com/", "Product: " );
您还可以尝试正则表达式,因为.replaceAll
函数接受正则表达式
String product = url.replaceAll( "http:.*\/", "Product: " );
请注意,我不是正则表达式专家,您应该创建自己的正则表达式。此选项将替换每个字符串执行以下操作:
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);
试试这个-
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);
如何:通过编写对replace方法的第二个调用?如何
url.replace(“http://fitness.com/“,”产品:“)。替换(“,”)。替换…
谢谢。你能推荐实现的任何其他变体吗?我为你添加了另一个东西,你也可以尝试一下,但你不认为,你的示例只会取代这个:http://fitness.com/
?但不是这样:http://www.fitness.com/
我需要更换both@EvgEvg我已经更新了我的答案。对不起,我没有把问题读对。