简体   繁体   中英

Finding fields in String java regular expression

I am not good at Java regular expressions.

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. (image, height, width...)
  • Group 3: The value of the property.

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\\"
  2. 481

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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