简体   繁体   English

在String Java正则表达式中查找字段

[英]Finding fields in String java regular expression

I am not good at Java regular expressions. 我不擅长Java正则表达式。

I have following text 我有以下文字

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

I want to extract image: , height and width from above text. 我想从上面的文本中提取图像:,高度和宽度。 Could someone help me writing regular expression to achieve it ? 有人可以帮我写正则表达式来实现吗?

If this is your exact String 如果这是您的确切字符串

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

Then try the following (Crude): 然后尝试以下(粗略):

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

Thats one way of doing it, another (better) would be to use a Pattern 那是一种实现方式,另一种(更好)的方式是使用模式

This regex will match a property and its associated value. 此正则表达式将匹配属性及其关联的值。 You will have to iterate through every match it finds in your source string to get all the information you want. 您将必须遍历在源字符串中找到的每个匹配项,以获取所需的所有信息。

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

You have three capture groups. 您有三个捕获组。 Two of which you are interested in: 您对其中两个感兴趣:

  • Group 1: The name of the property. 第1组:属性的名称。 (image, height, width...) (图片,高度,宽度...)
  • Group 3: The value of the property. 第3组:财产的价值。

Here is a breakdown of the regex: 这是正则表达式的细分:

(\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.

Try this regex: 试试这个正则表达式:

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

You will get two groups. 您将获得两组。

eg, 例如,

  1. height=\\"481\\" 身高= \\“ 481 \\”
  2. 481 481

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM