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-\2in some regex engines like Python'sremodule)
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 capturesRCas the first group and0as the second. Replacing givesRC-0followed by the remaining digits, resulting in the correct 12-character output. - For input
RC100003282, the first group capturesRC1, the second captures0, leading toRC1-0plus 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
相关产品推荐
相关产品推荐

