2011-08-03 39 views
1

我想檢查一個字符串是否包含#。 然後如果它包含#,我想在#之後找到內容。如何查找Java中是否存在特殊字符

例如,

  • test#1 - 這將返回我1
  • test*1 - 這不應該返回任何東西。
  • test#123Test - 這應該返回123Test

請讓我知道。提前Thanx。

+0

請澄清你的意思是「不應該返回任何東西」 - 如果你要將它封裝在一個方法中,你必須返回* something * - 你想要一個空字符串,或者爲空,例如?或者你想讓它拋出一個異常?你有'regex'的標籤,但是你有什麼理由要使用正則表達式呢? –

回答

2
// Compile a regular expression: A hash followed by any number of characters 
Pattern p = Pattern.compile("#(.*)"); 

// Match input data 
Matcher m = p.matcher("test#1"); 

// Check if there is a match 
if (m.find()) { 

    // Get the first matching group (in parentheses) 
    System.out.println(m.group(1)); 
} 
4

我會用簡單的字符串操作,而不是一個正則表達式:

int index = text.indexOf('#'); 
return index == -1 ? "" : text.substring(index + 1); 

(我假設「不應該返回任何」表示「返回空字符串」在這裏 - 你可以改變它)

相關問題