views:

512

answers:

5

I have this lines of text the number of quotes could change like:

Here just one "comillas"
But I also could have more "mas" values in "comillas" and that "is" the "trick"
I was thinking in a method that return "a" list of "words" that "are" between "comillas"

how I obtain the data between the quotes the result should be?:

www.eg.com, 192.57.42.11
comillas
mas, comillas, trick
a, words, are, comillas

A: 
String line = "if(getip(document.referrer)==\"www.eg.com\" || getip(document.referrer)==\"192.57.42.11\"";
StringTokenizer stk = new StringTokenizer(line, "\"");
stk.nextToken();
String egStr = stk.nextToken();
stk.nextToken();
String ipStr = stk.nextToken();
jsight
I allready try your solution this and using StrTokenizer from Apache commons and works but the trouble here is that it could be more than just 2 pair of quotes, maybe just one pair, or maybe more
atomsfat
A: 

Firstly, please note that you should user equals() rather than ==. "==" by default asks if they are the same instance in memory, which in Strings can sometimes be the case. With myString.equals("...") you're comparing the values of the Strings.

As for how do you obtain the values between the quotes I'm not sure what you mean. "..." is an actual object. Alternatively you could do:

String webUrl = "www.eg.com";

Stephane Grenier
I'm not sure the line of text he's parsing is Java source code. It could be another script that he's trying to read from a Java program to extract some information.
erickson
I'm guessing the text is JavaScript source.
Tom Hawtin - tackline
+1  A: 

You can use a regular expression to fish out this sort of information.

Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(line);
while (m.find()) {
  System.out.println(m.group(1));
}

This example assumes that the language of the line being parsed doesn't support escape sequences for double-quotes within string literals, contain strings that span multiple "lines", or support other delimiters for strings like a single-quote.

erickson
Sorry, I was missing a double quote there, myself!
erickson
Yes, your code makes the trick
atomsfat
A: 

If you are parsing an entire source file rather than just one line, a parser based on the grammar of the function might be a safer choice than trying to do this based on strings.

I am guessing that these would be string literals in your grammar.

Uri
A: 

Check out StringUtils in the Apache commons-lang library - it has a substringsBetween method.

String lineOfText = "if(getip(document.referrer)==/"www.eg.com/" || getip(document.referrer)==/"192.57.42.11/"";

String[] valuesInQuotes = StringUtils.substringsBetween(lineOfText , "/"");

assertThat(valuesInQuotes[0], is("www.eg.com"));
assertThat(valuesInQuotes[1], is("192.57.42.11"));
SingleShot