2013-06-24 197 views
0

我不擅長Java正則表達式。查找字符串java正則表達式中的字段

我具有以下文本

[[image:testimage.png||height=\"481\" width=\"816\"]] 

我想提取圖像:高度和寬度從上方的文本。有人能幫我寫正則表達式來實現它嗎?

+0

的好工具的試驗和錯誤:[正則表達式編輯器(http://myregexp.com/signedJar.html) – johnchen902

+0

另一個好的工具是[RegexPlanet](HTTP:// www.regexplanet.com/) –

+0

你在問題結尾處缺少一些東西......「我有n」? – NeverHopeless

回答

1

試試這個正則表達式:

((?:image|height|width)\D+?([a-zA-Z\d\.\\"]+)) 

您將獲得兩個組。

例如,

  1. height=\"481\"
  2. 481
1

如果這是你的確切字符串

[[image:testimage.png||height=\"481\" width=\"816\"]] 

那就試試下面的(原油):

String input = // read your input string 
String regex = ".*height=\\\\\"(\\d+)\\\\\" width=\\\\\"(\\d+)" 
String result = input.replaceAll(regex, "$1 $2"); 
String[] height_width = result.split(" ") 

那是一個做這件事的方式,另一個(更好)是使用一個Pattern

1

這個正則表達式將匹配一個屬性及其相關的值。你將不得不遍歷它在你的源字符串中找到的每一個匹配,以獲得你想要的所有信息。

(\w+)[:=]("?)([\w.]+)\2 

你有三個捕捉組。其中您感興趣的其中兩種:

  • 組1:屬性的名稱。 (圖像,高度,寬度...)
  • 組3:屬性的值。

這裏是正則表達式的細分:

(\w+)  #Group 1: Match the property name. 
[:=]  #The property name/value separator. 
("?)  #Group 2: The string delimiter. 
([\w.]+) #Group 3: The property value. (Accepts letters, numbers, underscores and periods) 
\2   #The closing string delimiter if there was one. 
相關問題