2013-06-24 126 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. 
相关问题