I need to create the regex that will match such string:
AA+1.01*2.01,BB*2.01+1.01,CC
Order of * and + should be any I've created the following regex:
^(([A-Z][A-Z](([*+][0-9]+(\.[0-9])?[0-9]?){0,2}),)*[A-Z]{2}([*+][0-9]+(\.[0-9])?[0-9]?){0,2})$
But the problem is that with this regex + or * could be used twice but I only need any of them once so the following strings matches should be:
AA+1*2,CC - true
AA+1+2,CC - false (now is true with my regex)
AA*1+2,CC - true
AA*1*2,CC - false (now is true with my regex)
Either of the [+*]
should be captured first and then use negative lookahead
to match the other one.
Regex: [AZ]{2}([+*])(?:\\d+(?:\\.\\d+)?)(?!\\1)[+*](?:\\d+(?:\\.\\d+)?),[AZ]{2}
Explanation:
[AZ]{2}
Matches two upper case letters.
([+*])
captures either of +
or *
.
(?:\\d+(?:\\.\\d+)?)
matches number with optional decimal part.
(?!\\1)[+*]
looks ahead for symbol captured and matched the other one. So if +
is captured previously then *
will be matched.
(?:\\d+(?:\\.\\d+)?)
matches number with optional decimal part.
,[AZ]{2}
matches ,
followed by two upper case letters.
To match the first case AA+1.01*2.01,BB*2.01+1.01,CC
which is just a little advancement over previous pattern, use following regex.
Regex: (?:[AZ]{2}([+*])(?:\\d+(?:\\.\\d+)?)(?!\\1)[+*](?:\\d+(?:\\.\\d+)?),)+[AZ]{2}
Explanation: Added whole pattern except ,CC
in first group and made it greedy by using +
to match one or more such patterns.
To get a regex to match your given example, extended to an arbitrary number of commas, you could use:
^(?:[A-Z]{2}([+*])?\d*\.?\d*(?!\1)[+*]?\d*\.?\d*,?)*$
Note that this example will also allow a trailing comma. I'm not sure if there is much you can do about that.
If the trailing comma is an issue:
^(?:[A-Z]{2}([+*])?\d*\.?\d*(?!\1)[+*]?\d*\.?\d*,?)*?(?:[A-Z]{2}([+*])?\d*\.?\d*(?!\2)[+*]?\d*\.?\d*?)$
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.