Makky
Makky

Reputation: 17461

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 ?

Upvotes: 0

Views: 327

Answers (3)

Francis Gagnon
Francis Gagnon

Reputation: 3675

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.

Upvotes: 1

NeverHopeless
NeverHopeless

Reputation: 11233

Try this regex:

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

You will get two groups.

e.g.,

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

Upvotes: 1

Java Devil
Java Devil

Reputation: 10959

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

Upvotes: 1

Related Questions