如何用正则表达式匹配带千分位的6数字符串中的第4个数字?
Let's break down why your current regex is grabbing multiple results, then tweak it to target exactly the 4th number you need.
The Issue with Your Current Regex
Your regex (?<= )(\d*,*\d*\.\d*)(?= \d*,*\d*\.) is too loose:
- The positive lookbehind
(?<= )only checks for a single preceding space, which applies to every number except the first one. - The positive lookahead
(?= \d*,*\d*\.)looks for a space followed by any number with a decimal, which works for every number except the last one. - That’s why it ends up matching the 2nd, 3rd, and 4th numbers instead of just the 4th.
Solution 1: Capture the 4th Number with a Non-Capturing Prefix
This approach explicitly matches the first three numbers (plus their trailing spaces) as a throwaway non-capturing group, then captures the 4th number cleanly:
^(?:\d+(?:,\d+)*\.\d+ ){3}(\d+(?:,\d+)*\.\d+)
Let’s unpack this:
^: Anchors the match to the start of the string (avoids accidental partial matches later on).(?:...): Non-capturing group (we don’t need to save the first three numbers).\d+(?:,\d+)*: Matches the integer part, including optional thousand separators (like35,362or0).\.\d+: Matches the mandatory decimal part (like.843or.000).: Matches the trailing space after each of the first three numbers.
{3}: Repeats the non-capturing group exactly 3 times (covers the first three numbers).(\d+(?:,\d+)*\.\d+): Capturing group that grabs the 4th number using the same valid number pattern.
Solution 2: Use a Precise Positive Lookbehind
If you don’t want to include the prefix in your match at all, use a positive lookbehind to confirm exactly three valid numbers come before the 4th:
(?<=^(?:\d+(?:,\d+)*\.\d+ ){3})\d+(?:,\d+)*\.\d+
This works like the first solution, but uses a lookbehind to validate the prefix instead of including it. The result is just the 4th number, no extra capturing group required.
Testing with Your Example String
For your input:
35,362.843 1,261.94 0.000 35,362.843 1,257.43 44,466,154.16
Both regexes will match exactly: 35,362.843
内容的提问来源于stack exchange,提问作者goleastro

