Home > Blockchain >  Java - How to validate regex expression with multiple parentheses then extract the components from t
Java - How to validate regex expression with multiple parentheses then extract the components from t

Time:10-05

I have an input string like:

abc(123:456),def(135.666:3434.777),ghi("2015-06-07T09:01:05":"2015-07-08")

Basically, it is (naive idea with regex):

[a-zA-Z0-9] (((number)|(quoted datetime)):((number)|(quoted datetime)))(,[a-zA-Z0-9] (((number)|(quoted datetime)):((number)|(quoted datetime)))) ?

How can I make a regex pattern in Java to validate that the input string follows this pattern and then I can extract the values [a-zA-Z0-9] and ((number)|(quoted datetime)):((number)|(quoted datetime)) from them?

CodePudding user response:

You can use

(\w )\((\d (?:\.\d )?|\"[^\"]*\"):(\d (?:\.\d )?|\"[^\"]*\")\)

See the regex demo.

In Java, it can be declared as:

String regex = "(\\w )\\((\\d (?:\\.\\d )?|\"[^\"]*\"):(\\d (?:\\.\\d )?|\"[^\"]*\")\\)";

Details:

  • (\w ) - Group 1: one or more word chars
  • \( - a ( char
  • (\d (?:\.\d )?|\"[^\"]*\") - Group 2: one or more digits optionally followed with . and one or more digits, or ", zero or more chars other than " and then a " char
  • : - a colon
  • (\d (?:\.\d )?|\"[^\"]*\") - Group 3: one or more digits optionally followed with . and one or more digits, or ", zero or more chars other than " and then a " char
  • \) - a ) char
  • Related