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

C#如何提取字符串中单引号包裹的文本内容?

C#提取单引号包裹的文本内容

首先明确:原字符串里的'dana's font'存在未转义单引号,会造成语法歧义,必须先调整为转义形式(比如'dana\'s font')才能正确解析。

方法一:正则表达式

用正则匹配带转义单引号的包裹内容,表达式'(?:\\.|[^'])*'可以精准匹配:

  • ':匹配开头单引号
  • (?:\\.|[^'])*:匹配转义字符(如\')或非单引号的任意字符,(?:...)表示非捕获组
  • ':匹配结尾单引号

C#代码示例:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = " 'john', 'michile,k', 'dana\\'s font' ";
        Regex quoteRegex = new Regex(@"'(?:\\.|[^'])*'");
        MatchCollection matches = quoteRegex.Matches(input);
        
        foreach (Match match in matches)
        {
            // 替换转义符还原成目标格式,直接输出match.Value则保留转义
            Console.WriteLine(match.Value.Replace("\\'", "'"));
        }
    }
}

运行后输出:

'john'
'michile,k'
'dana's font'

方法二:手动遍历解析

如果不想用正则,也可以手动遍历字符串,跟踪是否处于单引号包裹状态,遇到转义字符就跳过后续字符:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string input = " 'john', 'michile,k', 'dana\\'s font' ";
        List<string> extracted = new List<string>();
        bool isInQuote = false;
        int quoteStart = -1;

        for (int i = 0; i < input.Length; i++)
        {
            char current = input[i];
            // 遇到转义符,跳过下一个字符
            if (current == '\\' && i + 1 < input.Length)
            {
                i++;
                continue;
            }
            // 进入单引号包裹状态,记录起始位置
            if (current == '\'' && !isInQuote)
            {
                isInQuote = true;
                quoteStart = i;
            }
            // 退出单引号包裹状态,提取当前段内容
            else if (current == '\'' && isInQuote)
            {
                isInQuote = false;
                string segment = input.Substring(quoteStart, i - quoteStart + 1);
                extracted.Add(segment);
            }
        }

        foreach (string item in extracted)
        {
            Console.WriteLine(item.Replace("\\'", "'"));
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:03:26