如何用RegExp从字符串中提取数字?
| in a String Hey there! Let's fix that regex issue so you can pull all the numbers from your string, including the ones after the | character.
The Core Problem
When you only get the first 3 digits with \d+, it's almost always because you haven't enabled the global matching flag (usually denoted as g in regex engines). By default, regex stops after finding the first match—turning on global mode tells it to hunt down every valid match in the string.
Solutions Based on Your String Structure
1. Extract All Sequences of Digits (Anywhere in the String)
If you just need every group of consecutive numbers (like 123 and 4567 from a string like abc123|4567def), use this regex with global mode:
\d+
Example usage in JavaScript:
const inputStr = "Your string here, e.g., 123|45678"; const allNumberGroups = inputStr.match(/\d+/g); // Returns ["123", "45678"]
In Python, you'd use re.findall() which inherently looks for all matches:
import re input_str = "Your string here, e.g., 123|45678" all_number_groups = re.findall(r'\d+', input_str) // Returns ['123', '45678']
2. Target Numbers Specifically Around |
If your string follows a strict [numbers]|[numbers] structure (like 123|456), you can use a regex that captures each side separately:
(\d+)\|(\d+)
This creates two capture groups: the first holds the numbers before |, the second holds those after. Example in Python:
import re input_str = "123|456" match_result = re.search(r'(\d+)\|(\d+)', input_str) if match_result: before_pipe = match_result.group(1) # "123" after_pipe = match_result.group(2) # "456"
3. Extract Individual Digits (Even If Split by Non-Numbers)
If you need every single digit (not just consecutive groups—like pulling 1,2,3,4,5,6 from 12a34|5b6), use \d with global mode:
\d
Example in JavaScript:
const inputStr = "12a34|5b6"; const individualDigits = inputStr.match(/\d/g); // Returns ["1","2","3","4","5","6"]
Quick Check
Make sure in your regex tool you've toggled the global match option—usually a checkbox labeled "g" or "Global". That's the most common reason you weren't seeing matches after the |!
内容的提问来源于stack exchange,提问作者Dawid Wawrzynek

