【问题标题】:How to extract string in Java如何在Java中提取字符串
【发布时间】:2012-05-13 20:11:51
【问题描述】:

例如,我有一个字符串如下:

<http://www.w3.org/2000/01/rdf-schema#label> "Telecommunications law"@en <http://en.wikipedia.org/wiki/> 

提取子字符串最简单的方法是什么:

Telecommunication law

请注意子字符串包含一个空格。

【问题讨论】:

标签: java string substring


【解决方案1】:
public static void main(String args[]){
String yourString = "<http://www.w3.org/2000/01/rdf-schema#label> \"Telecommunications law\"@en <http://en.wikipedia.org/wiki/>";
        String tokens[] = yourString.split("\"");

        for(int i = 0; i < tokens.length; i++){
            if(tokens[i].equals("Telecommunications law")){
                System.out.println(tokens[i]);
            }
        }
    }

【讨论】:

    【解决方案2】:

    你可以使用模式和匹配器:

    Pattern p = Pattern.compile("\".*\"");
    Matcher m = p.matcher(s);
    
    if(m.find()){
       String resultString = m.group();
    }
    

    在您的情况下,resultString 将包含 ["Telecommunications law"],如果您不想保留它们,您可以修剪双引号。

    【讨论】:

      【解决方案3】:
          public static void main(String[] args) {
       String str = "http://www.w3.org/2000/01/rdf-schema#label \"Telecommunications law\"@en http://en.wikipedia.org/wiki/" ;
      
       String temp = str.substring(str.indexOf('\"')+1, str.indexOf('\"',str.indexOf('\"')+1));
       System.out.print(temp);
      
          }
      

      【讨论】:

        【解决方案4】:

        “提取字符串”是什么意思?

        获取第一次出现的字符串是:

        int index = string.indexOf("Telecommunications law");
        

        获取第一个括号和第二个括号之间的内容的最有效方法是:

        final String test="http://www.w3.org/2000/01/rdf-schema#label \"Telecommunications law\"@en http://en.wikipedia.org/wiki/";
        final int firstIndex=test.indexOf('\"');
        final int lastIndex=test.indexOf('\"',firstIndex+1);
        final String result=test.substring(firstIndex+1,lastIndex);
        System.out.println(result);
        

        【讨论】:

        • @andriod developer from that string 我只需要电信法。
        • 再次,您想要括号之间的内容吗?或者您只是想检查指定的字符串是否存在?无论哪种方式,我都使用我编写的代码回答了这两个问题。
        • 我不明白。如果您的意思是如何检查字符串是否存在,只需检查您从第一个代码中获得的整数是否为非负数。
        【解决方案5】:

        String.split()"上的字符串,并选择返回数组中的第二个元素:

        String tokens[] = yourString.split("\"");
        
        // tokens[1] will contain Telecommunications law
        

        【讨论】:

        • 我想使用正则表达式提取子字符串。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        相关资源
        最近更新 更多