[英]Regex match pattern plus rest of the string until next dot, comma or space
假設我有一個字符串WORK-232-3213-2323
。 已知可能的案例場景:
WORK-232-3213-2323, some text
WORK-232-3213-2323. some text
WORK-232-3213-2323.xlsx
WORK-232-3213-2323 some text
WORK-232-3213-2323/some text
格式WORK-232-3213-2323-some text
,但是這種情況不需要處理
我當前的正則表達式能夠使用WORK-232-3213-2323
模式捕獲所需的字符串,但作為 output 我得到-232-3213-2323
。 如何讓它在字符串中捕獲WORK-
加上文本的 rest 直到下一個空格、點、斜杠或逗號?
當前正則表達式: WORK-(.*?)[\s]
C#:
Regex pattern = new Regex("WORK-(.*?)[\s]");
string result = pattern.Match(myString).Groups[1].Value
您可以使用匹配而不使用捕獲組,並使用否定字符 class 不包括逗號、點或空白字符。
\bWORK-[^.,\s]+
\bWORK-
匹配 WORK 前面有一個單詞邊界以防止部分匹配[^.,\s]+
否定字符 class匹配除.
,
或一個空白字符string[] strings = {
"WORK-232-3213-2323, some text",
"WORK-232-3213-2323. some text",
"WORK-232-3213-2323.xlsx",
"WORK-232-3213-2323 some text",
"WORK-232-3213-2323/some text"
};
string pattern = @"\bWORK-[^.,\s]+";
foreach (String s in strings) {
Console.WriteLine(Regex.Match(s, pattern).Value);
}
Output
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323/some
如果您不想匹配最后一行,則可以使用捕獲組並匹配.
,
或后面的空格字符
\b(WORK-[^.,\s\/]+)[.,\s]
例如使用相同的示例字符串:
string pattern = @"\b(WORK-[^.,\s\/]+)[.,\s]";
foreach (String s in strings) {
Console.WriteLine(Regex.Match(s, pattern).Groups[1].Value);
}
Output
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323
WORK-232-3213-2323
在我看來,您可以使用以下模式來處理您的所有情況,以及可能發生的情況:
\bWORK(?:-[0-9]+)+
查看在線演示
我不是c#
中的英雄,所以我使用了一些我能找到的代碼來測試這個:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var s = @"WORK-232-3213-2323, some text";
var pattern = @"\bWORK(?:-[0-9]+)+";
Regex r = new Regex(pattern);
Match m = r.Match(s);
if (m.Success)
{
Console.WriteLine(m.Value);
}
}
}
或者,您可以使用\bWORK(?:-\d+)+
並使用Regex r = new Regex(pattern, RegexOptions.ECMAScript);
使用 ECMAScript 選項集。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.