RegEx for matching special patterns

iSpark :

I'm trying to match a String like this:62.00|LQ+2*2,FP,MD*3 "Description" Where the decimal value is 2 digits optional, each user is characterized by two Chars and it can be followed by

(\+[\d]+)? or (\*[\d]+)? or none, or both, or both in different order

like:

LQ*2+4 | LQ+4*2 | LQ*2 | LQ+8 | LQ

Description is also optional

What i have tried is this:

Pattern.compile("^(?<number>[\\d]+(\\.[\\d]{2})?)\\|(?<users>([A-Z]{2}){1}(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?))((,[A-Z]{2})(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?)))*)(\\s\\\"(?<message>.+)\\\")?$");

I need to get all the users so i can split them by ',' and then further regex my way into it.But i cannot grab anything out of it.The desired output from

62.00|LQ+2*2,FP,MD*3 "Description"

Should be:

62.00

LQ+2*2,FP,MD*3

Description

Accepted inputs should be of these kind:

62.00|LQ+2*2,FP,MD*3

30|LQ "Burgers"

35.15|LQ*2,FP+2*4,MD*3+4 "Potatoes"

35.15|LQ,FP,MD

Pushpesh Kumar Rajwanshi :

The precise regex to match the inputs you described should be fulfilled by this regex,

^(\d+(?:\.\d{1,2})?)\|([a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?(?:,[a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?)*)(?: +(.+))?$

Where group1 will contain the number that can have optional decimals upto two digits and group2 will have the comma separated inputs as you described in your post and group3 will contain the optional description if present.

Explanation of regex:

  • ^ - Start of string
  • (\d+(?:\.\d{1,2})?) - Matches the number which can have optional 2 digits after decimal and captures it in group1
  • \| - Matches literal | present in your input after the number
  • ([a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?(?:,[a-zA-Z]{2}(?:(?:\+\d+(?:\*\d+)?)|(?:\*\d+(?:\+\d+)?))?)*) - This part matches two letters followed by any combination of + followed by number and optionally having * followed by number OR * followed by number and optionally having + followed by number exactly either once or whole of it being optional and captures it in group2
  • (?: +(.+))? - This matches the optional description and captures it in group3
  • $ - Marks end of input

Regex Demo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92714&siteId=1