2012-02-07 69 views
-1

我需要實現以下幾點:字符串的處理在Java中

「$首選項」字符串中的「什麼東西$首選項(東西 東西)」應返回。 $ prefs由字母a-zAz 和數字0-9組成。 「$」總是在那裏。

尋找$prefs的開頭是沒有問題的,但是找到最終的結果會更棘手。如上所述,$prefs也可能是$prefssdf,其次幾乎是任何東西,如(,,,&&,什麼不是。

有沒有辦法做這樣的事情:

while(string.elementAt(i) == [a-zA-Z0-9]){ 
    result += string.elementAt(i); 
} 

一個例子:

我有以下字符串:

Select * from test where $prefs(select * from test2 where $prefs2); 

我需要提取表達式所有出現的$前綴,所以在這種情況下,它是$prefs$prefs2。我如何最有效地做到這一點?

+1

對不起,但我只是不明白你在問什麼。你能更具體並舉例嗎? – templatetypedef 2012-02-07 22:21:14

+0

你不應該在你的例子中提取'$ prefs'和'$ prefs2'嗎? – talnicolas 2012-02-07 22:33:10

+0

你說得對,修好了,謝謝! – deimos1988 2012-02-07 22:41:13

回答

1
if(Character.isDigit(a) || (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z')) { 
     // a is [a-zA-Z0-9] 
    } 
3

爲什麼不使用regex

String str = "something something $prefs(something something)"; 
Matcher matcher = Pattern.compile("\\$[a-zA-Z0-9]+").matcher(str); 
if (matcher.find()) { 
    System.out.println(str.substring(matcher.start(),matcher.end())); 
} else { 
    System.out.println("no match"); 
} 

正則表達式走的是一條$簽名和字母/數字跟隨它。

+0

你可能想用\\ w(一個「單詞」字符)代替[a-zA-Z0-9],儘管它也包含下劃線字符(但我認爲這是對這個用例的一個獎勵)。 – 2012-02-07 23:00:09

+0

呵呵,'str.substring(matcher.start(),matcher.end()'當然會和'matcher.group()'一樣。 – 2012-02-07 23:02:03

0

你可以看看正則表達式(here)和$匹配允許的字符後,發現部分。

1

這個答案假設這是作業。通常我會推薦在這裏使用完整的正則表達式。

所以你有while循環找出哪個是好的。

while (isKeywordCharacter(string.charAt(i))) { 
    //... 
} 

接下來的問題是什麼是這個方法的最佳實施:

public boolean isKeywordCharacter(char character) { 
    return //? 
} 

最透明和有效的可能是這樣的:

通過提取一個名爲「isKeywordCharacter」方法開始
return (character >= 'a' && character <= 'z') || ...; 

鑑於最自我記錄可能是這樣的:

return String.valueOf(character).matches("[a-zA-Z0-9]");