2015-12-16 111 views
6

我想使用Java中的正則表達式來提取特定的字符串。我目前有這種模式:正則表達式匹配Java中字符串的開頭和結尾

pattern = "^\\a.+\\sed$\n"; 

假設匹配以「a」開頭並以「sed」結尾的字符串。這不起作用。我錯過了什麼 ?

刪除模式末尾的\ n行,並將其替換爲「$」: 仍然無法匹配。正則表達式在我看來是合法的。

我想提取的是來自temp字符串的「a sed」。

String temp = "afsgdhgd gfgshfdgadh a sed afdsgdhgdsfgdfagdfhh"; 
       pattern = "(?s)^a.*sed$"; 
         pr = Pattern.compile(pattern); 

       math = pr.matcher(temp); 
+0

試試這個'^a。* sed $' – nafas

+0

是您尋找的「sed」嗎? – nafas

回答

3

UPDATE

要匹配a sed,所以你可以使用a\\s+sed如果只有空白ased之間:現在

String s = "afsgdhgd gfgshfdgadh a sed afdsgdhgdsfgdfagdfhh"; 
Pattern pattern = Pattern.compile("a\\s+sed"); 
Matcher matcher = pattern.matcher(s); 
while (matcher.find()){ 
    System.out.println(matcher.group(0)); 
} 

IDEONE demo

如果有可能什麼sed之間a,使用回火貪婪令牌:

Pattern pattern = Pattern.compile("(?s)a(?:(?!a|sed).)*sed"); 
             ^^^^^^^^^^^^^ 

another IDEONE demo

原來的答案

與您正則表達式的主要問題是\n末。 $是字符串的結尾,並且您試圖在字符串結束後再匹配一個字符,這是不可能的。另外,\\s與空白符號相匹配,但您需要字面s

您需要刪除\\ S和\n,使.匹配換行,也實在是advisbale使用*量詞允許0符號之間:

pattern = "(?s)^a.*sed$"; 

See the regex demo

正則表達式匹配:

  • ^ - 串的開始
  • a - 字面a
  • .* - 0個或多個的任何字符(因爲(?s)改性劑使得.匹配包括一個換行的任何字符)
  • sed - 文字字母序列sed
  • $ - 字符串的結尾
+0

見https://regex101.com/r/lY3qD0/1 –

+0

請檢查我的更新。我認爲其中一個解決方案應該適合你。 –

+0

如果有選項卡或只有空格,這項工作是否可行?謝謝!不存在匹配「字符開始」和「字符結束」的普通正則表達式嗎? –

1

temp字符串不能匹配patte RN (?s)^a.*sed$,因爲這種模式說,你temp字符串必須開始與字符一個結束與序列sed的,這是情況並非如此。您的字符串在「sed」序列後面有尾隨字符。 如果你只是想提取一個......的sed整個字符串的一部分,請嘗試使用非錨定模式,並使用Matcher classfind()方法「一* sed的。」:

Pattern pattern = Pattern.compile("a.*sed"); 
Matcher m = pattern.matcher(temp); 
if (m.find()) 
{ 
    System.out.println("Found string "+m.group()); 
    System.out.println("From "+m.start()+" to "+m.end()); 
} 
相關問題