简体   繁体   English

如何在Java中提取字符串

[英]How to extract string in Java

For example, I have a string as below: 例如,我有一个字符串如下:

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

What is the easiest way to extract the substring: 提取子字符串的最简单方法是什么:

Telecommunication law

Please note that the substring contains a space. 请注意,子字符串包含一个空格。

You could use Pattern and Matcher : 您可以使用Pattern和Matcher:

Pattern p = Pattern.compile("\".*\"");
Matcher m = p.matcher(s);

if(m.find()){
   String resultString = m.group();
}

In your case, resultString will contain ["Telecommunications law"] and you can trim the double quotes if you don't want to keep them. 在您的情况下,resultString将包含[“电信法”],如果您不想保留双引号,则可以修剪双引号。

String.split() the string on " , and select the second element in the returned array: String.split()对串" ,并选择返回的数组中的第二个元素:

String tokens[] = yourString.split("\"");

// tokens[1] will contain Telecommunications law

what do you mean "extracting the string" ? 你是什​​么意思“提取字符串”?

getting the first occurence of the string is by: 获取字符串的第一次出现是通过:

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

the most efficient way of getting what is in between the first parenthesis and the second is by: 获取第一个括号和第二个括号之间的内容的最有效方法是:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM