【问题标题】:How to remove strings inside brackets?如何删除括号内的字符串?
【发布时间】:2013-03-07 19:59:06
【问题描述】:

我有单词列表,我必须删除括号内的字符串列表

day[1.0,264.0]
developers[1.0,264.0]
does[1.0,264.0]
employees[1.0,264.0]
ex[1.0,264.0]
experts[1.0,264.0]
fil[1.0,264.0]
from[1.0,264.0]
gr[1.0,264.0]

我应该得到

day

developers

does
.
.
.
.

这种方法正确吗?

String rep=day[1.0,264.0];  
String replaced=rep.replace("[","]","1.0","2");

这种方法正确吗?

Pattern stopWords = Pattern.compile("\\b(?:i|[|]|1|2|3|...)\\b\\s*",Pattern.CASE_INSENSITIVE);    
Matcher matcher = stopWords.matcher("I would like to do a nice novel about nature AND people");    
String clean = matcher.replaceAll("");

【问题讨论】:

  • 尝试自己了解哪种变体有效。

标签: java regex string replace


【解决方案1】:

比目前其他建议的方法稍微简单一些。

String s = "day[1.0,264.0]";
String ofInterest2 = s.substring(0, s.indexOf("["));

会给你输出

day

【讨论】:

    【解决方案2】:

    使用String#replaceAll(regex, repl)

     String rep="day[1.0,264.0]";
     rep = rep.replaceAll("\\[.*]","");
    

    regex:\\[.*] as [ 是正则表达式世界中的一个特殊字符(元字符),您必须将其转义将反斜杠将其视为文字。.* 用于 b/w '[anything在这里]'

    【讨论】:

      【解决方案3】:

      什么都不用替换它们

      rep.replaceAll("\\[.*\\]", "");
      

      【讨论】:

        【解决方案4】:

        只需用“[”标记您的字符串并获取第一部分。

        StringTokenizer st = new StringTokenizer(str, "[");
        String part1 = st.nextToken();
        

        【讨论】:

          【解决方案5】:

          这也允许括号后面的东西

               String rep="day[1.0,264.0]";
               int firstIndex = rep.indexOf('[');
               int secondIndex = rep.indexOf(']');
               String news = rep.substring(0, firstIndex) +    rep.substring(secondIndex+1,rep.length());
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-03
            • 1970-01-01
            • 2017-05-06
            • 2018-06-08
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多