c# Regex- 删除仅开发特殊章程组合的字符串
c# Regex- Remove string which developed only combination of special charter
我正在寻找可以忽略仅由 All special charters.
组合而成的字符串的正则表达式
例子
List<string> liststr = new List<string>() { "a b", "c%d", " ", "% % % %" ,"''","&","''","'"}; etc...
我需要这个的结果
{ "a b", "c%d"}
使用这个:
.*[A-Za-z0-9].*
它至少匹配一个字母数字字符。这样做,它将接受任何不仅是 symbols/special 个字符的字符串。它执行您想要的输出,请参见此处:demo
您可以使用非常简单的正则表达式,例如
Regex regex = new Regex(@"^[% &']+$");
在哪里
[% &']
是您希望包含的特殊字符列表
例子
List<string> liststr = new List<string>() { "a b", "c%d", " ", "% % % %" ,"''","&","''","'"};
List<string> final = new List<string>();
Regex regex = new Regex(@"^[% &']+$");
foreach ( string str in liststr)
{
if (! regex.IsMatch(str))
final.Add(str);
}
输出结果为
final = {"a b", "c%d"}
您也可以使用它来匹配没有 任何 Unicode 字母的字符串:
var liststr = new List<string>() { "a b", "c%d", " ", "% % % %", "''", "&", "''", "'" };
var rx2 = @"^\P{L}+$";
var res2 = liststr.Where(p => !Regex.IsMatch(p, rx2)).ToList();
输出:
我还建议将正则表达式对象创建为 private static readonly
字段,并带有 Compiled
选项,这样性能就不会受到影响。
private static readonly Regex rx2 = new Regex(@"^\P{L}+", RegexOptions.Compiled);
... (and inside the caller)
var res2 = liststr.Where(p => !rx2.IsMatch(p)).ToList();
我正在寻找可以忽略仅由 All special charters.
组合而成的字符串的正则表达式例子
List<string> liststr = new List<string>() { "a b", "c%d", " ", "% % % %" ,"''","&","''","'"}; etc...
我需要这个的结果
{ "a b", "c%d"}
使用这个:
.*[A-Za-z0-9].*
它至少匹配一个字母数字字符。这样做,它将接受任何不仅是 symbols/special 个字符的字符串。它执行您想要的输出,请参见此处:demo
您可以使用非常简单的正则表达式,例如
Regex regex = new Regex(@"^[% &']+$");
在哪里
[% &']
是您希望包含的特殊字符列表
例子
List<string> liststr = new List<string>() { "a b", "c%d", " ", "% % % %" ,"''","&","''","'"};
List<string> final = new List<string>();
Regex regex = new Regex(@"^[% &']+$");
foreach ( string str in liststr)
{
if (! regex.IsMatch(str))
final.Add(str);
}
输出结果为
final = {"a b", "c%d"}
您也可以使用它来匹配没有 任何 Unicode 字母的字符串:
var liststr = new List<string>() { "a b", "c%d", " ", "% % % %", "''", "&", "''", "'" };
var rx2 = @"^\P{L}+$";
var res2 = liststr.Where(p => !Regex.IsMatch(p, rx2)).ToList();
输出:
我还建议将正则表达式对象创建为 private static readonly
字段,并带有 Compiled
选项,这样性能就不会受到影响。
private static readonly Regex rx2 = new Regex(@"^\P{L}+", RegexOptions.Compiled);
... (and inside the caller)
var res2 = liststr.Where(p => !rx2.IsMatch(p)).ToList();