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

如何移除空格关联短横线但保留连字符(含多连字符)

Hey there, let's get this string processing issue sorted out for you!

First, let's restate your requirements clearly to make sure we're on the same page:

Need to remove hyphens that are either at the start/end of words, or standalone groups of hyphens separated by spaces, but keep hyphens that are part of a word (including multiple consecutive hyphens within a word).
Example input: This- -is - a test-sentence. -Test- --- One-Two--Three---Four----.
Expected output: This is a test-sentence. Test One-Two--Three---Four.

The Problem With Your Current Regex

Your existing pattern (?<!\w)\-(?!\-)|(?<!\-)\-(?!\w) only targets single hyphens that aren't adjacent to other hyphens or word characters. It can't handle:

  • Standalone groups of multiple hyphens (like ---)
  • Multiple hyphens attached to the start/end of words (like -Test- or Four----.)

The Solution

We need a regex that targets all groups of hyphens that aren't sandwiched between word characters. Here's a working approach:

Step 1: Remove Unwanted Hyphen Groups

Use this regex to match and remove hyphens that are either:

  • At the start of a sequence (not preceded by a word character), OR
  • At the end of a sequence (not followed by a word character)
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string sentence = "This- -is - a test-sentence. -Test- --- One-Two--Three---Four----.";
        // Match hyphen groups that aren't between word characters
        string hyphenPattern = @"(?<!\w)-+|-+(?!\w)";
        string tempResult = Regex.Replace(sentence, hyphenPattern, "");
        
        // Clean up any extra spaces created by removing hyphens
        string finalResult = Regex.Replace(tempResult, @"\s+", " ");
        
        Console.WriteLine(finalResult);
        // Output: "This is a test-sentence. Test One-Two--Three---Four."
    }
}

How This Works

  1. Hyphen Removal Regex:

    • (?<!\w)-+: Matches one or more hyphens that are not preceded by a word character (e.g., -is, ---)
    • -+(?!\w): Matches one or more hyphens that are not followed by a word character (e.g., This-, Four----.)
    • Together, these cover all unwanted hyphen groups while leaving hyphens inside words (like test-sentence or One-Two--Three---Four) untouched.
  2. Space Cleanup:

    • After removing hyphens, you might end up with multiple consecutive spaces (e.g., -is - a becomes is a). The regex \s+ replaces any group of spaces with a single space to fix this.

Testing the Solution

When you run this code with your example input, it produces exactly the expected output:
This is a test-sentence. Test One-Two--Three---Four.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:24:43