如何修改正则表达式匹配分号后不含逗号的数字
Alright, let's get this regex sorted for you so it only grabs those target numbers right after semicolons, without dragging in commas or extra text.
What's Wrong With Your Current Pattern
Your current regex \d+[,]+[^,]+[^,0-2] is over-matching because it's built to capture digits plus commas and non-comma characters—way more than just the numbers you care about. That's why you're getting extra substrings attached to your matches.
The Right Regex for the Job
We need to target exactly the digits that come right after a semicolon, and stop before the following comma. Here are two solid options:
Option 1: Positive Lookahead (Clean, Direct Matches)
If your regex tool/engine supports lookarounds (which most modern ones do—Python, JavaScript, etc.), use this:
;(\\d+)(?=,)
Let's break this down:
;: Explicitly matches the semicolon that precedes your target number(\\d+): Captures one or more digits—this is the number you want(?=,): A "positive lookahead" that checks the digits are immediately followed by a comma, but doesn't include the comma in the match. Perfect for stopping right at the number.
Option 2: Capture Group (For Older Regex Engines)
If you're working with an engine that doesn't support lookarounds, use a capture group to extract just the digits:
;(\\d+),
When you run this, the full match will include ;X,, but the first capture group (group 1) will hold just the number X—that's what you'll want to use.
Testing With Your Input
For your sample string:
C07KTL89290003;1,C07KTL89290003,1;2,C07KTL89290003,0;3,...;40,C07KTL89290003,0
Either regex will pull out 1, 2, 3, ..., 40 perfectly—no commas, no extra characters, just the numbers you need.
Bonus: Restrict to 1-40 Only
If you want to make sure you never match numbers outside your 1-40 range, you can narrow the regex further:
;(1?\\d|2[0-9]|3[0-9]|40)(?=,)
This breaks down to:
1?\\d: Matches 1-19 (the1?allows for single-digit numbers 1-9 too)2[0-9]: Matches 20-293[0-9]: Matches 30-3940: Matches exactly 40
This way, even if a random number like 41 or 0 pops up after a semicolon, it won't get matched.
内容的提问来源于stack exchange,提问作者Scott Ruiter

