I want to match regex such that the sign(+ or -) in one group and figure in other group. It may possible that figure comes without any sign(+ or -)
Example
[-] 87.90
[+] 87.78
(-) 87.90
(+) 87.78
89
-89.56
- 89.98
I have used below regular expression
^\W*(\-|\+|)\W*(\d+(\.\d+)?)
By this I am getting empty in group 1 If I use
^\W*(\-|\+)\W*(\d+(\.\d+)?)
then 3rd figure will not match. So in short I want to match figure with (+ or -) or without any sign.
Group 1 is empty because the \\W*
greedily matches all non-word characters, that is, all parentheses and signs.
You should specify the literal parentheses in the pattern and a character class will be a more natural construct to match either a +
or a -
:
(?:\(?([-+])\)?)?\p{Zs}*(\d+(\.\d+)?)
See regex demo (if you need a full string match, use ^
at the start and $
at the end of the pattern).
Regex matches:
(?:\\(?([-+])\\)?)?
- an optional non-capturing group ( (?:...)
) that matches a (
optionally, followed by a plus or minus (Group 1), and then by an optional )
\\p{Zs}*
- zero or more whitespace symbols (\\d+(\\.\\d+)?)
- (Group 2) one or more digits followed by an optional capturing group (Group 3) that matches a period followed by one or more digits. Result:
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.