gpt4 book ai didi

c# - 用于匹配重复的连续标点符号的正则表达式,但 3 个句点除外

转载 作者:太空狗 更新时间:2023-10-29 20:20:46 28 4
gpt4 key购买 nike

我有正则表达式

(\p{P})\1 

成功匹配重复的连续标点字符,如

;;
,,
\\

,但我需要排除 3 个句点(省略号)标点符号。

...

最佳答案

小心,因为某些方法无法成功匹配 .## 形式的字符串(即重复标点符号前的“.”)。假设那是应该匹配的东西。

此解决方案满足以下要求:-

  1. 匹配重复的标点符号。
  2. 省略号 (...) 不匹配。
  3. 匹配两个点 (..) 和四个或更多点。
  4. 如果前面或后面有点,则匹配重复的标点符号,例如.##

这是正则表达式:

(?>(\p{P})\1+)(?<!([^.]|^)\.{3})

解释:

  • ?>表示 atomic grouping .具体来说,扔掉所有的回溯位置。这意味着如果 '...' 无法匹配,则不要后退并尝试匹配 '..'。
  • (\p{P})\1+)表示匹配 2 个或更多标点符号字符 - 你已经有了这个。
  • (?<!([^.]|^)\.{3})表示从重复字符匹配的末尾向后搜索,如果发现三个点前面没有点或字符串开头,则失败。这使三个点失败,同时允许两个点或四个点或更多点起作用。

以下测试用例通过并说明使用:

string pattern = @"(?>(\p{P})\1+)(?<!([^.]|^)\.{3})";

//Your examples:
Assert.IsTrue( Regex.IsMatch( @";;", pattern ) );
Assert.IsTrue( Regex.IsMatch( @",,", pattern ) );
Assert.IsTrue( Regex.IsMatch( @"\\", pattern ) );
//two and four dots should match
Assert.IsTrue( Regex.IsMatch( @"..", pattern ) );
Assert.IsTrue( Regex.IsMatch( @"....", pattern ) );

//Some success variations
Assert.IsTrue( Regex.IsMatch( @".;;", pattern ) );
Assert.IsTrue( Regex.IsMatch( @";;.", pattern ) );
Assert.IsTrue( Regex.IsMatch( @";;///", pattern ) );
Assert.IsTrue( Regex.IsMatch( @";;;...//", pattern ) ); //If you use Regex.Matches the matches contains ;;; and // but not ...
Assert.IsTrue( Regex.IsMatch( @"...;;;//", pattern ) ); //If you use Regex.Matches the matches contains ;;; and // but not ...

//Three dots should not match
Assert.IsFalse( Regex.IsMatch( @"...", pattern ) );
Assert.IsFalse( Regex.IsMatch( @"a...", pattern ) );
Assert.IsFalse( Regex.IsMatch( @";...;", pattern ) );

//Other tests
Assert.IsFalse( Regex.IsMatch( @".", pattern ) );
Assert.IsFalse( Regex.IsMatch( @";,;,;,;,", pattern ) ); //single punctuation does not match
Assert.IsTrue( Regex.IsMatch( @".;;.", pattern ) );
Assert.IsTrue( Regex.IsMatch( @"......", pattern ) );
Assert.IsTrue( Regex.IsMatch( @"a....a", pattern ) );
Assert.IsFalse( Regex.IsMatch( @"abcde", pattern ) );

关于c# - 用于匹配重复的连续标点符号的正则表达式,但 3 个句点除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18821518/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com