Parsing quoted text in java

Is there an easy way to parse quoted text as a string in java? I have lines like this for parsing:

author="Tolkien, J.R.R." title="The Lord of the Rings"
publisher="George Allen & Unwin" year=1954 

and all I want is Tolkien, JRR, The Lord of the Rings, George Allen and Unwin, 1954 as strings.

+5
source share
3 answers

You can use regex like

"(.+)"

It will match any character between quotation marks. In Java:

Pattern p = Pattern.compile("\\"(.+)\\"";
Matcher m = p.matcher("author=\"Tolkien, J.R.R.\"");
while(matcher.find()){
  System.out.println(m.group(1));      
}

Note that group (1) is used, this is the second match, the first, group (0), is a full string with quotes

You can also use a substring to select everything except the first and last 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;
}
+5

, , .

String.split(). , .

, String word: "hello", "", :

myStr = string.split("\"")[1];

.

,

myStr = string.split("word: \"")[1].split("\"")[0];

word: " "

, , word: " , . , .

, . . Split , . , "\\"= \ . - , .

!

+3

, ? , String.split().

- , ( StringBuffer for;-)) , " - ".

, , , : , , . , , , , ? \" , . (, html) ?

- , , Java Lexer (, JFlex), , .

, while, , =" StringBuffer, ", , - ( , ). , (: =") .

+1

All Articles