我正在尝试使用linq
和regex
方法来删除所有字母和数字字符,并仅在字符串中保留标点符号:
string input = ": hello; world; 2019>how?.are,you. .i'm good}and-you[?ok";
在输出列表中为每个未在同一字符串中除以字符或数字的标记分割:
:
;
;
>
?.
,
..
'
}
-
[?
任何指南或示例都会有所帮助
答案 0 :(得分:2)
我想您可以使用以下内容
给出
string input = ": hello; world; 2019>how?.are,you. .i'm good}and-you[?ok";
选项1
var results = Regex.Replace(input, @"[\w]", Environment.NewLine)
.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Replace(" ", ""));
选项2
var results2 = Regex.Matches(input, @"[\p{P} ]*")
.OfType<Match>()
.Where(x => !string.IsNullOrWhiteSpace(x.Value))
.Select(x => x.Value.Replace(" ", ""));
输出
:
;
;
>
?.
,
.
.
'
}
-
[?
注意 :在一种模式下可能有更好的方法
答案 1 :(得分:1)
使用Linq,您可以使用与this response on how to strip punctuation from a string非常相似的东西,您可以使用:
var result = input.Where(p => char.IsPunctuation(p)).ToArray();