2012-06-07 30 views
0

我想找到在java中字符串中以「#」開頭的唯一第一個單詞。標誌和單詞之間不能有空格。只找到第一個字從一個特殊字符開始java

串「喜#如何是你#」應給予輸出爲:

如何

我曾試圖與正則表達式,但還是沒能找到一個合適的模式。請幫助我。

謝謝。

+0

那你試試? – TimK

+0

嘗試匹配以下模式#[a-zA-z] –

+0

「ab cd#ef #gh」'應該是什麼結果? – Pshemo

回答

1

試試這個

replaceFirst("^.*?(#\\S+).*$", "$1"); 

不完全美麗,但應該工作。

這假設字符串有這樣的標記。如果沒有,那麼你可能要檢查它是否與正則表達式匹配提取令牌之前:

matches("^.*?(#\\S+).*$"); 

注意,此方法將在"sdfkhk#sdfhj sdf"匹配"#sdfhj"

如果你想排除這種情況,你可以修改正則表達式爲"^.*?(?<= |^)(#\\S+).*$"

+0

replaceFirst(「^。*?(#\\ S +)。* $」,「$ 1」);完美的作品..謝謝nhahtdh。 –

0

你可以試試這個正則表達式:

"[^a-zA-Z][\\S]+?[\\s]" 

,除非你知道你正在尋找特定的字符在這種情況下,

"#[\\S]+?[\\s]" 
+0

'[/ S]'匹配'/'或'S',並且'[^/S] /'或'S'。如果你想匹配任何非空白字符,那就是'[\ S]'或者(甚至更好)只是'\ S'。在Java字符串文字中,您必須避開反斜線:'「\\ S」'。 –

+0

@AlanMoore你是對的。我習慣於在php上下文中使用正則表達式,並且一直困惑\和/。 –

1
String str ="hi #how are # you"; 
if (str.contains("#")) { 
     int pos = str.indexOf("#"); 

     while (str.charAt(pos + 1) == ' ') 
      pos++; 


     int last = str.indexOf(" ", pos + 1); 

     str = str.substring(pos + 1, last); 
     System.out.println(str); 
    } 
else{ 

} 

輸出開始:如何

+0

這不符合「#」並給你一個索引超出界限的錯誤嗎? –

+0

@Hans感謝看到編輯的答案... – MAC

+1

失敗的情況下:'「你好#####f #f# – nhahtdh

1

我假設xx#xx是錯誤的單詞。我多數民衆贊成真正試試這個(如果不使用模式"#(\\w+)"m.group(1)代替m.group(2)

String str ="ab cd#ef #gh"; 
Pattern pattern=Pattern.compile("(^|\\s)#(\\w+)"); 
Matcher m=pattern.matcher(str); 
if(m.find()) 
    System.out.println(m.group(2)); 
else 
    System.out.println("no match found"); 

"ab cd#ef #gh"結果 - >gh

"#ab cd#ef #gh"結果 - >ab

相關問題