【问题标题】:get substring and replace with previous text in java获取子字符串并用java中的先前文本替换
【发布时间】:2012-12-30 12:31:26
【问题描述】:

我通过 getWebsite() 从 bean 获取爬取的网站。我有时会得到网站http://www.stackoverflow.com,有时会得到http://stackoverflow.com。我的问题是我想用“info@st​​ackoverflow.com”替换 setEmail() 到 bean 而不是那个。是否可以借助 substring 和 replaceAll 方法?

我在下面尝试了自己

    String s=str.substring(0,11);
    System.out.println("String s (0,11) :"+s);
    String string=str.substring(0,7);
    System.out.println("string  (0,7):"+string);
    String name=str.substring(11);
    String name1=str.substring(7);
    System.out.println("name  :"+name);
    boolean b=((!(s.length()==11)) || (string.length()==7))? true : ((!(string.length()==7)) || (s.length()==11))? false : true ;
    System.out.println(b);
    if(b==true)
    {
        System.out.println("condition TRUE");
        String replaceString=string.replaceAll(string,"info@");
        System.out.println("replaceString  :"+replaceString+name1);
    }
    if(b==false) 
    {
        System.out.println("condition FALSE");
        String replaceString=s.replaceAll(s,"info@");
        System.out.println("replaceString  :"+replaceString+name);
    }

【问题讨论】:

  • 抱歉,这看起来像是代码混淆比赛的获胜者。你真正想做什么?

标签: java string replaceall


【解决方案1】:

一个例子

String orig = "Hello World!";

String repl = orig.substring(6, 11); // "World"

String newstr = orig.replaceAll(repl, "user1937829"); // Hello user1937829!

在你的情况下,你不需要http://(www)

String newstr = orig.replaceAll("www", "").replaceAll("http://", "info@");

如果orighttp://www.stackoverflow.comhttp://stackoverflow.comnewstr 将等于info@stackoverflow.com

希望这就是你想要的。

【讨论】:

    【解决方案2】:

    需要在替换函数中使用正则表达式

    String str1= "http://www.stackoverflow.com";
    String str2 = "http://stackoverflow.com";
    System.out.println(str1.replaceAll("http:\\/\\/(www\\.)?","info@"));
    System.out.println(str2.replaceAll("http:\\/\\/(www\\.)?","info@"));
    

    【讨论】:

      【解决方案3】:

      好的,不要给自己带来困难,只需将字符串中的http:// 或其他可能的模式使用str.replaceAll() 替换为info@。推荐使用正则表达式

      String str = "http://www.stackoverflow.com";
      
      str = str.replaceAll("http:\\/\\/(www\\.)?","info@");
      System.out.println(str);
      

      http://rextester.com/SJD79549

      我的问题是?你想做什么?

      【讨论】:

        猜你喜欢
        • 2020-04-05
        • 2016-07-19
        • 1970-01-01
        • 2015-05-31
        • 2023-03-25
        • 1970-01-01
        • 2011-06-30
        • 1970-01-01
        相关资源
        最近更新 更多