You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用RegExp从字符串中提取数字?

Extracting Numbers Including Those After | 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:14:27