正则表达式用于匹配重复的连续标点字符,但 3 个句点除外
本文关键字:字符 句点 用于 连续 正则表达式 | 更新日期: 2023-09-27 18:31:35
>我有正则表达式
('p{P})'1
成功匹配重复的连续标点字符,例如
;;
,,
''
,但我需要排除 3 个句点(省略号)标点符号。
...
请注意,因为某些方法将无法成功匹配.##
形式的字符串(即重复标点符号之前的".")。假设这是应该匹配的东西。
此解决方案满足以下要求:-
- 匹配重复的标点符号。
- 省略号 (...) 不匹配。
- 两个点 (..) 和四个或更多点匹配。
- 重复的标点符号在前面或后面有点时匹配,例如
.##
这是正则表达式:
(?>('p{P})'1+)(?<!([^.]|^)'.{3})
解释:
-
?>
表示原子分组。具体来说,扔掉所有回溯头寸。这意味着如果"..."不匹配,然后不要退后一步并尝试匹配".."。 -
('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 ) );
避免匹配...
(?<![.])(?![.]{3})('p{P})'1
(?<!'.)(?!'.{3}(?!'.))('p{P})'1+
这将匹配任何重复的标点符号(包括....
或......
等),除非它是字符串...
。例如:
; -- No Match
;; -- Match
,, -- Match
,,,, -- Match
'' -- Match
... -- No Match
.... -- Match