tamir
tamir

Reputation: 29

how to match a list of parameters in java with regex

I need to match lists like:

a = 9, b=5 , c = 15

The values can be also of type double, string, char and boolean, or a previous variable (for example, a=b). I've tried to arrange the following regular expression

([A-Za-z0-9](=)?(,)?)|((=)?,\s*\d+)*

but no success achieved so far. Any help would be appreciated.

Upvotes: 0

Views: 805

Answers (2)

Carlos
Carlos

Reputation: 357

Try this:

Solution 1

(\s*[A-Za-z0-9]\s*=\s*\S*(,)?)+

If you want to capture all the elements in the list then:

Solution 2

 ((\s*[A-Za-z0-9]\s*=\s*\S*(,)?)+)

YCF_L solutions looks good also except for one small variation:

^([a-zA-Z0-9]+\s*=\s* [a-zA-Z0-9]+\s*,?\s*)*

The second part ignores the fact that you could have a double value. It will still match, but if you were to capture the values as in Solution 2 above but using the YCF_L solution then the decimal portion will be dropped.

Here is great link on capturing repeated groups:

http://www.regular-expressions.info/captureall.html

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

You can use this regex ([a-zA-Z0-9]+\s*=\s*[a-zA-Z0-9]+) :

regex demo

matches :

a = 9 
b=5
c = 15
a=b
b= true
s = false

Edit

If you want to matche a list like this for example :

a = 9 , b=5 , c = 15 , a=b , b= true , s = false

then you can use a regex like this ^([a-zA-Z0-9]+\s*=\s*[a-zA-Z0-9]+\s*,?\s*)*

regex demo 2

in jave you can use :

boolean m = "a = 9 , b=5 , c = 15 , a=b , b= true , s = false".
                matches("^([a-zA-Z0-9]+\\s*=\\s*[a-zA-Z0-9]+\\s*,?\\s*)*");//true

Upvotes: 4

Related Questions