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

用于检查、添加或替换逗号的自定义正则表达式需求

Solution: Single Regex-Based String Normalization

Got it, let's tackle this problem! You need a streamlined regex workflow to convert all those varied input formats into the consistent comma-separated two-character chunk format. Here's a clean, efficient approach that works across most popular regex engines (JavaScript, Python, Java, etc.):

Core Implementation

The solution combines two key tasks—cleaning existing separators and inserting new ones—into either a single replace call (for engines supporting conditional logic) or a simple two-step regex pipeline:

For Engines with Conditional Replacements (e.g., JavaScript)

You can use one replace call with a regex that matches both unwanted separators and the positions where commas need to be added:

const normalizeInput = (input) => {
  return input.replace(/[\s,]|(?<=.{2})(?!$)/g, (match) => {
    // Replace spaces/commas with empty string; insert comma at valid positions
    return match === ' ' || match === ',' ? '' : ',';
  });
};

For Engines Without Conditional Logic (e.g., Basic Python)

If your regex engine doesn't support callback functions, use two sequential replaces (still a straightforward, single workflow):

import re

def normalize_input(input_str):
    # Step 1: Strip all spaces and commas to get a pure character string
    cleaned = re.sub(r'[\s,]', '', input_str)
    # Step 2: Insert commas after every two characters (except end of string)
    return re.sub(r'(?<=.{2})(?!$)', ',', cleaned)

Test Case Validation

Let’s confirm this works with all your provided examples:

  • ABCDEF → AB,CD,EF ✅
  • ABCD → AB,CD ✅
  • ABCDE → AB,CD,E ✅
  • AB CD EF → AB,CD,EF ✅
  • AB CD → AB,CD ✅
  • AB CD E → AB,CD,E ✅
  • AB,CD,EF → AB,CD,EF ✅
  • AB,CD,E → AB,CD,E ✅

Regex Breakdown

Let’s unpack the key patterns:

  • [\s,]: Matches any whitespace or comma (these get replaced with an empty string to clean the input)
  • (?<=.{2})(?!$): A combination of positive lookbehind and negative lookahead:
    • (?<=.{2}): Ensures we’re positioned after at least two characters
    • (?!$): Ensures we’re not at the very end of the string
    • This targets the exact spots where a comma should be inserted

内容的提问来源于stack exchange,提问作者Ashish Lohia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:55:31