【问题标题】:Java Replace String with two (or more) expressionsJava 用两个(或更多)表达式替换字符串
【发布时间】:2016-02-17 08:46:24
【问题描述】:

我想替换这个字符串: - http://fitness.com/gorilla-bumpers - http://www.fitness.com/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 中再添加一个替换项? 提供几个变体将不胜感激。谢谢你

【问题讨论】:

  • 怎么样:通过编写第二次调用 replace 方法?
  • url.replace("http://fitness.com/", "Product: ").replace("","").replace....怎么样

标签: java regex replace str-replace


【解决方案1】:

就这样吧:

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

你也可以尝试正则表达式,因为.replaceAll 函数需要正则表达式

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

请注意,我不是正则表达式方面的专家,您应该创建自己的。这个替换了每个http://BLABLA/ 字符串

【讨论】:

  • 我又给你加了一个,你也可以试试
【解决方案2】:

执行以下操作:

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

【讨论】:

  • 谢谢。你能建议任何其他的实现变体吗?
【解决方案3】:

试试这个-

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

【讨论】:

  • 但是你不觉得,你的例子只会取代这个:http://fitness.com/?但不是这个:http://www.fitness.com/ 我需要同时替换两者
  • @EvgEvg 我已经更新了我的答案。对不起,我没有正确阅读问题。
猜你喜欢
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2021-06-25
  • 2015-05-11
相关资源
最近更新 更多