正则表达式匹配分号前两位数字及空格并替换的技术需求
Got it, let's sort out this string transformation for you. Here's a straightforward regex solution to get exactly the format you're after:
Step 1: Identify the Pattern to Remove
Each entry in your original string ends with the redundant suffix 0.0 0.0; (or 0.0 0.0; for the final entry). Our goal is to target this suffix and replace it with a clean comma + space separator.
Step 2: The Regular Expression
Use this regex pattern to match the unwanted portion:
\s+0\.0\s+0\.0;\s*
Let's break down what each part does:
\s+: Matches one or more whitespace characters (the spaces before the first0.0)0\.0: Matches the literal0.0(we escape the dot with\because it’s a special regex character that normally matches any character)\s+: Another set of one or more spaces between the two0.0values0\.0;: Matches the second0.0followed by a semicolon\s*: Optional trailing whitespace (handles any extra spaces after the final semicolon)
Step 3: Implement the Replacement
Depending on the tool or language you’re using, here’s how to apply this:
Example in Python
import re original_string = "-9.853418333333334 35.020405 0.0 0.0;-9.854273333333333 35.02038 0.0 0.0;-9.85452 35.01970166666667 0.0 0.0;-9.854205 35.019618333333334 0.0 0.0;-9.853418333333334 35.020405 0.0 0.0;" cleaned_string = re.sub(r'\s+0\.0\s+0\.0;\s*', ', ', original_string).rstrip(', ') print(cleaned_string)
This will output your desired format:
-9.853418333333334 35.020405, -9.854273333333333 35.02038, -9.85452 35.01970166666667, -9.854205 35.019618333333334, -9.853418333333334 35.020405
Example in Text Editors (e.g., Notepad++)
- Open the Find/Replace dialog (Ctrl+H)
- Check the "Regular expression" option
- Find what:
\s+0\.0\s+0\.0; - Replace with:
, - Click "Replace All"
- Clean up the trailing comma: find
, $and replace with nothing (check "Wrap around" if needed)
Why This Works
We’re directly targeting the predictable, redundant 0.0 0.0; suffix that follows each coordinate pair. By swapping that for a comma separator, we get the clean, comma-delimited list of coordinate pairs you need.
内容的提问来源于stack exchange,提问作者Theron Morgan-Brown

