保留字符串中分开的标记列表

时间:2019-04-09 01:46:51

标签: c# regex linq

我正在尝试使用linqregex方法来删除所有字母和数字字符,并仅在字符串中保留标点符号:

   string input = ": hello; world; 2019>how?.are,you. .i'm good}and-you[?ok";

在输出列表中为每个未在同一字符串中除以字符或数字的标记分割:

:
;
;
>
?.
,
..
'
}
-
[?

任何指南或示例都会有所帮助

2 个答案:

答案 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(" ", ""));

输出

:
;
;
>
?.
,
.
.
'
}
-
[?

Full Demo here

注意 :在一种模式下可能有更好的方法

答案 1 :(得分:1)

使用Linq,您可以使用与this response on how to strip punctuation from a string非常相似的东西,您可以使用:

var result = input.Where(p => char.IsPunctuation(p)).ToArray();