我正在尝试使用linq
andregex
方法来删除所有字母和数字字符并仅在字符串中保留标点符号:
string input = ": hello; world; 2019>how?.are,you. .i'm good}and-you[?ok";
在输出列表中拆分每个标记的输出列表,而不是在同一字符串中除以字符或数字:
:
;
;
>
?.
,
..
'
}
-
[?
任何指南或示例都会有所帮助
我想你可以使用以下
给定
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(" ", ""));
输出
:
;
;
>
?.
,
.
.
'
}
-
[?
注意:在一种模式中可能有更好的方法来做到这一点
使用 Linq,您可以使用与此响应非常相似的内容来了解如何从字符串中去除标点符号,您可以使用:
var result = input.Where(p => char.IsPunctuation(p)).ToArray();