2014-11-21 40 views
0

幾個星期前我發佈了這個問題,涉及使用Java中的正則表達式提取捕獲組,Extracting Capture Group Using Regex,並且我收到了一個工作答案。幾周前我還發布了這個問題,涉及使用正則表達式的字符替換,Replace Character in Matching Regex,並得到了比我從第一篇文章中獲得的更好的答案。我將通過示例快速說明。我有這樣一個字符串,我想提取從「ID」:使正則表達式更動態

String idInfo = "Any text up here\n" + 
       "Here is the id\n" + 
       "\n" + 
       "?a0 12 b5\n" + 
       "&Edit Properties...\n" + 
       "And any text down here"; 

而且在這種情況下,我所要的輸出僅僅是:

a0 12 b5 

但事實證明,可以在ID可以是任意數量的八位字節(只需要一個或多個八位字節),並且我希望我的正則表達式能夠基本解釋1個字節的ID,然後是任意數量的後續八位字節(從0到多個)。我在匹配正則表達式文章中的「替換字符」中收到了答案的人爲我做了一個類似但不同的用例,但我無法將此「更動態」的正則表達式移植到第一個用例中。

目前,我有...

Pattern p = Pattern.compile("(?s)?:Here is the id\n\n\\?([a-z0-9]{2})|(?<!^)\\G:?([a-z0-9]{2})|.*?(?=Here is the id\n\n\\?)|.+"); 
Matcher m = p.matcher(certSerialNum); 
String idNum = m.group(1); 
System.out.println(idNum); 

但它拋出一個異常。另外,我實際上喜歡使用模式中所有已知的相鄰文本,包括「這是ID \ n \ n \?」。和「\ n &編輯屬性...」。我需要做什麼修正才能使其工作?

+0

'?:Here'錯誤。開放口供在哪裏?再次檢查正則表達式。 – 2014-11-21 17:08:21

+0

你的意思是這個http://regex101.com/r/uT5cC0/4? – 2014-11-21 17:15:23

+0

要在字符串文本中使用模式編譯器解釋的反斜線字符(\\),必須將其轉義以防止它被解析爲字符轉義:'「... \\?...」 。當字符串解析器和模式編譯器以相同的方式解釋轉義時,這是可選的,例如序列'\ n'。 – 2014-11-21 17:48:40

回答

1

好像你想是這樣的,

String idInfo = "Any text up here\n" + 
     "Here is the id\n" + 
     "\n" + 
     "?a0 12 b5\n" + 
     "&Edit Properties...\n" + 
     "And any text down here"; 
Pattern regex = Pattern.compile("Here is the id\\n+\\?([a-z0-9]{2}(?:\\s[a-z0-9]{2})*)(?=\\n&Edit Properties)"); 
Matcher matcher = regex.matcher(idInfo); 
while(matcher.find()){ 
     System.out.println(matcher.group(1)); 
} 

輸出:(?S)

a0 12 b5 

DEMO