[英]Excluding duplicates from a string in results
我正在嘗試修改此正則表達式,使其不匹配重復項。
當前正則表達式:
[\""].+?[\""]|[^ ]+
示例字符串:
".doc" "test.xls", ".doc","me.pdf", "test file.doc"
預期結果:
".doc"
"test.xls"
"me.pdf"
但不是
".doc"
"test.xls"
".doc"
"me.pdf"
注意:
test file.doc
.doc
或".doc"
。在 C# 中,您可以使用簡單的正則表達式來提取所有有效匹配項,並使用.Distinct()
僅保留唯一值。
正則表達式很簡單:
"(?<ext>[^"]+)"|(?<ext>[^\s,]+)
請參閱正則表達式演示,您只需要 Group "ext" 值。
細節
"(?<ext>[^"]+)"
- "
, (group "ext") 除"
任何 1+ 個字符,然后"
|
- 或者(?<ext>[^\\s,]+)
- (group "ext") 除了空格和逗號之外的 1+ 個字符C# 代碼片段:
var text = "\".doc\" \"test.xls\", \".doc\",\"me.pdf\", \"test file.doc\".doc \".doc\"";
Console.WriteLine(text); // => ".doc" "test.xls", ".doc","me.pdf", "test file.doc".doc ".doc"
var pattern = "\"(?<ext>[^\"]+)\"|(?<ext>[^\\s,]+)";
var results = Regex.Matches(text, pattern)
.Cast<Match>()
.Select(x => x.Groups["ext"].Value)
.Distinct();
Console.WriteLine(string.Join("\n", results));
輸出:
.doc
test.xls
me.pdf
test file.doc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.