Identifying a String within a file such that it starts and ends with a quote
i am writing a scheme interpreter in Java. Files contain m开发者_运维问答any lines/words This is one of the lines in the file:
"xx'x v \"yyyyy\"... eee dddd ffff\\\n"
I have to identify it such that the whole string is returned, but in my program, it only reads "xx'x v \" and then reads the other words from " to \" Any help is highly appreciated
String text = "";
int nextString = t;
while(!isString(nextString)){
nextString = reader.read();
int next = peek();
if (nextString == '\\' && next =='"'){
nextString = reader.read();
if(Character.isSpaceChar(next)){
text+=" ";
}
}
text += (char) nextString;
}
return new StringToken(text, lineNumber);
}
if you don't want to use regular expression maybe you can use:
String text = "";
int nextString = t;
while(!isString(nextString)){
nextString = reader.read();
int next = peek();
if (nextString == '\\' && next =='"'){
nextString = reader.read();
text += (char) nextString;
nextString = reader.read();
}
if(Character.isSpaceChar(next)){
text+=" ";
}
text += (char) nextString;
}
return new StringToken(text, lineNumber);
}
Using regular expressions, for example:
[^\\]\"(.*[^\\])\"
This will only work if the first " is not the first character of the string. The string you want is the one enclosed between (). For example, if I pass \"garbage"Hello\"foo", it will get Hello\"foo (this is what you want if I understood right).
I actually don't know how regex's Java classes handle () in regexs.
精彩评论