目标:获取所有非字母数字字符,即使它们不连续。
设置: 我在 ASP.Net 页面上有一个文本框,它调用 TextChanged 上的 C# 代码隐藏方法。此事件处理程序针对 Regex 模式运行文本框输入。
问题:我无法创建正确的正则表达式模式来提取所有非字母数字字符。
这是字符串输入:string titleString = @"%2@#$%^&";
这些是我尝试过的 C# 正则表达式模式:
string titlePattern = @"(\b[^A-Za-z0-9]+)";
结果为 @#$%^&
(注意:如果我使用此输入字符串 %2@35%^&
,则上述正则表达式模式将识别 @
符号,然后是 %^&
),但绝不是前导 %
符号)。
string titlePattern = @"(\A[^A-Za-z0-9]+)";
结果为 %
string titlePattern = @"(\b\W[^A-Za-z0-9]+)";
结果为 @#$%^&
旁注:我也在一个 MS Visual Studio 控制台应用程序中运行它,它带有一个 foreach
循环,以便将所有无效字符放入一个集合中,我也使用网站测试输入和模式:http://regexstorm.net/tester
最佳答案
对您的选择字符串使用替换方法。
编辑:仔细阅读后我发现您想要相反的字符串。两者都在这里。
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string Source = @"H)*e/.?l\l{}*o ][W!~`@#""or^-_=+ld!";
string Trash = @"[^a-zA-Z0-9]";
string InvertedTrash = @"[a-zA-Z0-9]";
Output(Source, Trash);
Console.WriteLine($"{System.Environment.NewLine}Opposite Day!{System.Environment.NewLine}");
Output(Source, InvertedTrash);
Console.ReadKey();
}
static string TakeOutTheTrash(string Source, string Trash)
{
return (new Regex(Trash)).Replace(Source, string.Empty);
}
static void Output(string Source, string Trash)
{
string Sanitized = TakeOutTheTrash(Source, Trash);
Console.WriteLine($"Started with: {Source}");
Console.WriteLine($"Ended with: {Sanitized}");
}
}
}
关于c# - 如何使用正则表达式从输入字符串中提取所有非字母数字字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55304551/