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

Regex替换需求:在字符串首个0前添加连字符

Solution: Insert Hyphen Before First Zero in String

Alright, let's tackle this regex replacement problem. The goal is to add a hyphen immediately before the first occurrence of '0' in your 11-character input string, producing a 12-character output where no letters appear after the hyphen. Here's how to do it:

Regex Pattern & Replacement

The core approach uses a non-greedy capture to isolate the part before the first '0', then inserts the hyphen between that part and the '0'.

  • Match Pattern: ^(.*?)(0)
  • Replacement String: $1-$2 (use \1-\2 in some regex engines like Python's re module)

Breakdown of the Regex

  • ^: Anchors the match to the start of the string, ensuring we don't accidentally match '0's in unrelated positions later in the string.
  • (.*?): Non-greedy capture group that grabs all characters from the start up to (but not including) the first '0'. The ? makes the wildcard non-greedy, so it stops at the very first '0' instead of the last one.
  • (0): Captures the first '0' itself, so we can include it in the output right after the hyphen.

Code Examples

Here's how to implement this in common programming languages:

Python

import re

def format_target_string(s):
    # Optional validation to ensure input meets the 11-character requirement
    if len(s) != 11:
        raise ValueError("Input must be exactly 11 characters long")
    return re.sub(r'^(.*?)(0)', r'\1-\2', s)

# Test the provided examples
print(format_target_string("RC000030034"))  # Output: RC-000030034
print(format_target_string("RC100003282"))  # Output: RC1-00003282

JavaScript

function formatTargetString(str) {
    if (str.length !== 11) {
        throw new Error("Input must be exactly 11 characters long");
    }
    return str.replace(/^(.*?)(0)/, '$1-$2');
}

// Test cases
console.log(formatTargetString("RC000030034")); // "RC-000030034"
console.log(formatTargetString("RC100003282")); // "RC1-00003282"

Verification

  • For input RC000030034, the regex captures RC as the first group and 0 as the second. Replacing gives RC-0 followed by the remaining digits, resulting in the correct 12-character output.
  • For input RC100003282, the first group captures RC1, the second captures 0, leading to RC1-0 plus the rest of the digits.

This solution adheres to all your requirements: fixed input/output lengths, hyphen only before the first '0', and no letters after the hyphen.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:34