2009-09-24 17 views
14

我有這個文本行報價的數量可能會改變這樣的:如何在java中引用數據之間的數據?

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" 

我怎麼獲得引號之間的數據結果應該是?:

科米利亞斯
MAS,科米亞斯,招
一個,也就是說,是,科米利亞斯

+0

喔,你的意思是,這是文本行? – OscarRyz 2009-09-24 17:51:23

回答

34

您可以使用正則表達式來挖掘這類信息。

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

本示例假定該線的語言被解析不支持字符串常量內雙引號轉義序列,包含跨越多個「行」的字符串,或支持其他分隔符像單個串-引用。

+0

對不起,我錯過了一個雙引號,我自己! – erickson 2009-09-24 18:04:24

+0

是的,你的代碼製造詭計 – atomsfat 2009-09-24 18:20:42

0
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(); 
+1

我已經嘗試過你的解決方案,並使用Apache Commons中的StrTokenizer工作,但這裏的麻煩在於它可能不僅僅是2對引號,可能只是一對,或者更多 – atomsfat 2009-09-24 18:06:46

0

首先,請注意,您應該用戶相當於(),而不是==。 「==」默認詢問它們是否是內存中的相同實例,在Strings中有時可能是這種情況。使用myString.equals(「...」)來比較字符串的值。

至於你如何獲得引號之間的值我不確定你的意思。 「...」是一個實際的對象。或者你可以這樣做:

String webUrl =「www.eg.com」;

+2

我不確定文本行他解析的是Java源代碼。它可能是另一個腳本,他試圖從Java程序中讀取一些信息。 – erickson 2009-09-24 17:53:48

+0

我猜測文本是JavaScript源代碼。 – 2009-09-24 18:09:19

0

如果您解析整個源文件而不是一行,基於函數語法的解析器可能比嘗試基於字符串執行此操作更安全。

我猜測這些在您的語法中是字符串文字。

12

在Apache commons-lang庫中檢出StringUtils - 它有一個substringsBetween方法。

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

如果你想獲得所有ocurrences從文件

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class testReadQuotes { 


    public static void main(String args[]) throws IOException{ 

     Pattern patt = Pattern.compile("\"([^\"]*)\""); 
     BufferedReader r = new BufferedReader(new FileReader("src\\files\\myFile.txt")); 

     String line; 

     while ((line = r.readLine()) != null) { 

      Matcher m = patt.matcher(line); 

      while (m.find()) { 
      System.out.println(m.group(0)); 
      } 

     } 

    } 

} 
相關問題