简体   繁体   中英

Unable to match this string “18% on $25.56” with this regex “.*(\d+)%.*\$(\d+)(\.\d+)?$”. What am I doing wrong?

I'm trying to get the numbers out of a string that user inputs for calculating tip. The query could be "Calculate 18% tip on $25.56" or simply "18% $25.56"

I've built up this regex

.*(\d+)%.*\$(\d+)(\.\d+)?$

However, the first capturing group doesn't capture 18, just 8. What am I doing wrong ?

EDIT: Based on the answer below, I made my regex more error resilient. For matching a string like this

"Calculate18sdaasa%onasda$dsada25dasda.56aaddsadas dsad asdadas 18 sadasd 23 asdasd .56 asdasd"

I now have the regex as

.*?(\\d+).*?%.*?\\$.*?(\\d+).*?(\\.\\d+).*

This captures the first three numbers 18, 25 and .56 which is what I need.

Note that .* in the beginning of your RegEx is greedy, and that (\\d+) will also be satisfied with only matching a single-digit number. Thus, the starting .* kind of "steals" all but the last digit of your first number while (\\d+) still matches the last digit of the first number.

Do it like this instead:

.*?(\d+)%.*\$(\d+)(\.\d+)?$

.*? is non-greedy, that means, it will match as few characters as possible to satisfy the pattern.

尝试以下正则表达式模式:

\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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM