【问题标题】:pascal-like string literal regular expression类帕斯卡字符串文字正则表达式
【发布时间】:2026-01-18 07:00:02
【问题描述】:

我正在尝试将帕斯卡字符串文字输入与以下模式匹配:@"^'([^']|(''))*'$",但这不起作用。模式有什么问题?

public void Run()
{             
    using(StreamReader reader = new StreamReader(String.Empty))
    {
        var LineNumber = 0;
        var LineContent = String.Empty;

        while(null != (LineContent = reader.ReadLine()))
        {
            LineNumber++;

            String[] InputWords = new Regex(@"\(\*(?:\w|\d)*\*\)").Replace(LineContent.TrimStart(' '), @" ").Split(' ');

            foreach(String word in InputWords)
            {
                Scanner.Scan(word);
            }

        }
    }
}

我在输入字符串中搜索任何 pascal-comment 条目,将其替换为空格,然后将输入拆分为子字符串以将它们与以下内容匹配:

private void Initialize()
{
    MatchingTable = new Dictionary<TokenUnit.TokenType, Regex>();

    MatchingTable[TokenUnit.TokenType.Identifier] = new Regex
    (
        @"^[_a-zA-Z]\w*$",
        RegexOptions.Compiled | RegexOptions.Singleline
    );
    MatchingTable[TokenUnit.TokenType.NumberLiteral] = new Regex
    (
        @"(?:^\d+$)|(?:^\d+\.\d*$)|(?:^\d*\.\d+$)",
         RegexOptions.Compiled | RegexOptions.Singleline
    );
}
// ... Here it all comes together
public TokenUnit Scan(String input)
{                         
    foreach(KeyValuePair<TokenUnit.TokenType, Regex> node in this.MatchingTable)
    {
        if(node.Value.IsMatch(input))
        {
            return new TokenUnit
            {
                Type = node.Key                        
            };
        }
    }
    return new TokenUnit
    {
        Type = TokenUnit.TokenType.Unsupported
    };
}

【问题讨论】:

  • 什么是类似 Pascal 的字符串文字? This?
  • 你能显示一些输入字符串和预期结果吗?

标签: c# regex


【解决方案1】:

该模式似乎是正确的,尽管可以简化:

^'(?:[^']+|'')*'$

说明:

^      # Match start of string
'      # Match the opening quote
(?:    # Match either...
 [^']+ # one or more characters except the quote character
 |     # or
 ''    # two quote characters (= escaped quote)
)*     # any number of times
'      # Then match the closing quote
$      # Match end of string

如果您要检查的输入包含 Pascal 字符串以外的任何内容(例如,周围的空格),则此正则表达式将失败。

因此,如果您想使用正则表达式在较大的文本语料库中查找 Pascal 字符串,则需要删除 ^$ 锚。

如果你也想允许双引号,那么你需要增加正则表达式:

^(?:'(?:[^']+|'')*'|"(?:[^"]+|"")*")$

在 C# 中:

foundMatch = Regex.IsMatch(subjectString, "^(?:'(?:[^']+|'')*'|\"(?:[^\"]+|\"\")*\")$");

这个正则表达式将匹配字符串

'This matches.'
'This too, even though it ''contains quotes''.'
"Mixed quotes aren't a problem."
''

它不会匹配像这样的字符串

'The quotes aren't balanced or escaped.'
There is something 'before or after' the quotes.
    "Even whitespace is a problem."

【讨论】:

  • 我使用空格分割输入,每个字符串将其与某些词素类匹配。这就是我放锚的原因。据我了解,Pascal '''pascal-like'' string' 中的序列不合适。我说的对吗?
  • 如果你用空格分割你的输入,那么它也会在字符串中分割,不是吗?我将提供一些此正则表达式将匹配和不匹配的示例 - 您可能需要提供一些实际输入的示例(编辑您的问题并粘贴一些示例)。
  • 所以你对字符串文字是正确的。如果我用空格分割行,那么即使使用工作模式,我也无法以我的方式匹配它。那我该怎么办??感谢您的建议!
最近更新 更多