[英]Regex to match multiple number groups between two characters
我有一個如下所示的字符串:
<@399969178745962506> hello to <@!104729417217032192>
我有一本包含兩者的字典,如下所示:
{"399969178745962506", "One"},
{"104729417217032192", "Two"}
我的目標是將<@399969178745962506>
替換為該數字鍵的值,在本例中為One
Regex.Replace(arg.Content, "(?<=<)(.*?)(?=>)", m => userDic.ContainsKey(m.Value) ? userDic[m.Value] : m.Value);
我當前的正則表達式如下: (?<=<)(.*?)(?=>)
只匹配<
和>
之間的所有內容,在這種情況下會留下@399969178745962506
和@!104729417217032192
我不能忽略@
符號,因為!
標志不是每次都在那里。 所以最好只得到像\\d+
這樣的數字
我需要弄清楚如何只獲得<
和>
之間的數字,但我一生都無法弄清楚如何。
非常感謝任何幫助!
在 C# 中,您可以使用 2 種方法:基於環視(因為后視模式可以是可變寬度)和捕獲組方法。
可以輕松幫助您在正確的上下文中獲取數字的模式是
(?<=<@!?)\d+(?=>)
查看正則表達式演示
(?<=<@!?)
是需要<=
或<=!
緊接在當前位置的左側, (?=>)
是一個正向前瞻,它需要>
char 緊靠當前位置的右側。
您可以使用以下模式來捕獲預期<...>
子字符串中的數字:
<@!?(\d+)>
細節
<@
- 文字<@
子字符串!?
- 一個可選的感嘆號(\\d+)
- 捕獲匹配一位或多位數字的組 1>
- 文字>
符號。 請注意,您需要的值可以通過match.Groups[1].Value
訪問,如上面的代碼片段所示。
用法:
var userDic = new Dictionary<string, string> {
{"399969178745962506", "One"},
{"104729417217032192", "Two"}
};
var p = @"<@!?(\d+)>";
var s = "<@399969178745962506> hello to <@!104729417217032192>";
Console.WriteLine(
Regex.Replace(s, p, m => userDic.ContainsKey(m.Groups[1].Value) ?
userDic[m.Groups[1].Value] : m.Value
)
); // => One hello to Two
// Or, if you need to keep <@, <@! and >
Console.WriteLine(
Regex.Replace(s, @"(<@!?)(\d+)>", m => userDic.ContainsKey(m.Groups[2].Value) ?
$"{m.Groups[1].Value}{userDic[m.Groups[2].Value]}>" : m.Value
)
); // => <@One> hello to <@!Two>
請參閱C# 演示。
您可以使用非捕獲組來排除組內所需模式的部分:
(?<=<)(?:@?!?)(.*?)(?=>)
或者,您可以命名內部組並使用命名組來獲取它:
(?<=<)(?:@?!?)(?<yourgroupname>.*?)(?=>)
通過m.Groups["yourgroupname"].Value
訪問它 - 更多見 fe 如何訪問 .NET Regex 中的命名捕獲組?
正則表達式: (?:<@!?(\\d+)>)
詳情:
(?:)
非捕獲組
<@
中的字符匹配<@字面上
?
匹配零次和一次
(\\d+)
第一個捕獲組\\d+
匹配一個數字(等於 [0-9])
string text = "<@399969178745962506> hello to <@!104729417217032192>";
Dictionary<string, string> list = new Dictionary<string, string>() { { "399969178745962506", "One" }, { "104729417217032192", "Two" } };
text = Regex.Replace(text, @"(?:<@!?(\d+)>)", m => list.ContainsKey(m.Groups[1].Value) ? list[m.Groups[1].Value] : m.Value);
Console.WriteLine(text); \\ One hello to Two
Console.ReadLine();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.