问题
I am looking for regular expression by which I can ignore strings which is only combination of All special charters.
Example
List<string> liststr = new List<string>() { "a b", "c%d", " ", "% % % %" ,"''","&","''","'"}; etc...
I need result of this one
{ "a b", "c%d"}
回答1:
Use this one :
.*[A-Za-z0-9].*
It matches at least one alphanumeric character. Doing this, it will take any string that is not only symbols/special chars. It does the output you want, see here : demo
回答2:
You can use this, too, to match string without any Unicode letter:
var liststr = new List<string>() { "a b", "c%d", " ", "% % % %", "''", "&", "''", "'" };
var rx2 = @"^\P{L}+$";
var res2 = liststr.Where(p => !Regex.IsMatch(p, rx2)).ToList();
Output:
I also suggest creating the regex object as a private static readonly
field, with Compiled
option, so that performance is not impacted.
private static readonly Regex rx2 = new Regex(@"^\P{L}+", RegexOptions.Compiled);
... (and inside the caller)
var res2 = liststr.Where(p => !rx2.IsMatch(p)).ToList();
回答3:
You can use a very simple regex like
Regex regex = new Regex(@"^[% &']+$");
Where
[% &']
Is the list of special characters that you wish to include
Example
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);
}
Will give an output as
final = {"a b", "c%d"}
来源:https://stackoverflow.com/questions/29790137/c-sharp-regex-remove-string-which-developed-only-combination-of-special-charter