dav*_*vid 5 java string parsing string-parsing
有没有一种简单的方法可以将引用的文本解析为java的字符串?我有这样的行解析:
author="Tolkien, J.R.R." title="The Lord of the Rings"
publisher="George Allen & Unwin" year=1954
Run Code Online (Sandbox Code Playgroud)
我想要的只是Tolkien,JRR,指环王,George Allen和Unwin,1954年作为弦乐.
你可以使用正则表达式
"(.+)"
Run Code Online (Sandbox Code Playgroud)
它将匹配引号之间的任何字符.在Java中将是:
Pattern p = Pattern.compile("\\"(.+)\\"";
Matcher m = p.matcher("author=\"Tolkien, J.R.R.\"");
while(matcher.find()){
System.out.println(m.group(1));
}
Run Code Online (Sandbox Code Playgroud)
注意使用group(1),这是第二个匹配,第一个匹配,group(0),是带引号的完整字符串
在你可以使用子串来选择除第一个和最后一个char之外的所有内容:
String quoted = "author=\"Tolkien, J.R.R.\"";
String unquoted;
if(quoted.indexOf("\"") == 0 && quoted.lastIndexOf("\"")==quoted.length()-1){
unquoted = quoted.substring(1, quoted.lenght()-1);
}else{
unquoted = quoted;
}
Run Code Online (Sandbox Code Playgroud)
有一些奇特的模式正则表达式的废话,奇特的人和奇特的程序员喜欢使用。
我喜欢使用 String.split()。这是一个简单的函数,可以完成您需要它做的事情。
因此,如果我有一个字符串word: "hello"并且我想取出“hello”,我可以简单地这样做:
myStr = string.split("\"")[1];
这将根据引号将字符串切成位。
如果我想更具体,我可以这样做
myStr = string.split("word: \"")[1].split("\"")[0];
这样我就可以用word: "and来切割它"
当然,如果word: "重复两次就会遇到问题,这就是模式的用途。我认为您不必针对您的具体问题来处理该问题。
另外,要小心像 之类的字符。和 。Split 使用正则表达式,因此这些字符会触发有趣的行为。我认为"\\"=\会逃脱那些有趣的规则。如果我错了,有人纠正我。
祝你好运!