2012-01-05 69 views
1

我想匹配新行後的表達式。我正在使用gnu.regexp和標誌REG_MULTILINE。 Here's字符串我要檢查多行gnu正則表達式

Hello 
Dude 

我的做法是使用此正則表達式匹配。

String strRegExp = "^[Dd][Uu][Dd]"; 

但它不起作用。無法看到問題出在哪裏。 I'm運行這一切都在一個簡單的單元測試:提前

@Test 
public void testREMatchAtStartOfNewLine() 
throws Exception { 
    String strRegExp = "^[Dd][Uu][Dd]"; 
    int flags = RE.REG_MULTILINE; 
    String strText ="Hello\nDude"; 
    RE re = new RE(strRegExp, flags, RESyntax.RE_SYNTAX_PERL5); 
    REMatch match = re.getMatch (strText); 
    String strResult = ""; 
    if (match != null) { 
     strResult = match.substituteInto ("$0"); 
    } 
    assertEquals("Match at start of new line ", "Dud", strResult); // FAILS 
} 

感謝。 編輯: 爲了澄清,我使用以下的進口:

import gnu.regexp.RE; 
import gnu.regexp.REMatch; 
import gnu.regexp.RESyntax; 

回答

1

因爲主頁有一個破損的下載鏈接,你使用GNU Regex庫的任何原因? :)

無論如何,似乎在使用RESyntax.RE_SYNTAX_PERL5預計\r\n作爲行分隔符。替換\n\r\n似乎工作。

+0

謝謝,這對我幫助很大。 /r/n做得很對。 – AlfonsSocken 2012-01-05 13:49:14

1

我不知道你使用的正則表達式,但下面的工作對我來說:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
... 

@Test 
public void testREMatchAtStartOfNewLine() { 
    String strRegExp = ".*\n([Dd][Uu][Dd]).*"; 
    Pattern pattern = Pattern.compile(strRegExp); 
    String strText = "Hello\nDude"; 
    Matcher matcher = pattern.matcher(strText); 
    assertTrue(matcher.matches()); 
    assertEquals("Match at start of new line ", "Dud", matcher.group(1)); // WINS 
} 

通知的".*"在前面和模式的結束。默認情況下,Java正則表達式需要匹配整個字符串,所以這些都是必需的。