c# - 我可以为 C# 正则表达式定义自定义模式吗?

标签 c# regex

所以我想使用基本上是 \s (空格)的模式,只是我不想匹配不间断空格 (\160)。这将是一个非常长的字符串,用于定义除该字符之外的所有空白字符。有没有办法定义自定义模式并为其提供委托(delegate)?它只是 c => Char.IsWhiteSpace(c) && c != '\160'

谢谢。

最佳答案

在 .NET 正则表达式中,您可以使用 character class subtraction .

It makes it easy to match any single character present in one list (the character class), but not present in another list (the subtracted class). The syntax for this is [class-[subtract]]. If the character after a hyphen is an opening bracket, these flavors interpret the hyphen as the subtraction operator rather than the range operator. You can use the full character class syntax within the subtracted character class.

要从 \s 类中仅排除硬空间 (\u00A0),请使用

[\s-[\u00A0]]

参见regex demo

作为替代方案(因为字符类减法是 .NET 特定的功能),您始终可以依靠负向前瞻来限制泛型类(尽管此处的性能较差):

(?!\u00A0)\s

参见another demo

关于c# - 我可以为 C# 正则表达式定义自定义模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33041071/

相关文章:

regex - 是否有与 Perl 兼容的正则表达式来修剪字符串两侧的空格?

c# - 如何从 Team Foundation 获取工作项的用户帐户名?

c# - 更新后 css iframe 未在客户端上更新

c# - 在 set 属性中使用 console.ReadLine()

c# - 从原始响应中删除 HTTP header

Python 和 Regex 将书面数字转换为数字

c# - 加密字符串以匹配原始字符串的长度

c# - 当我使用 VPN 连接到 SQL Server 时,如何从查询中获取 SQL Server 2008 的端口号

javascript - 确保字符串仅包含数字、句点和可能的前导破折号

android - 如何使用正则表达式查找输入文本是否为 url