![](/img/trans.png)
[英]How to extract the contents of square brackets in a string of text in c# using Regex
[英]How separate words by excluding square brackets in C# using regex
我有一句話,比如“Hello there [Gesture:2.5]你好嗎?”我通過避開整個方括號將單詞分開。 例如“你好,你好嗎”。
我試圖將結腸前的單詞分開,但這不是我想要的。 這是我試過的代碼。
MatchCollection matches2 = Regex.Matches(avatarVM.AvatarText, @"([\w\s\[\]]+)");
上面的代碼只將“:”之前的單詞分開,其中還包括開頭方括號和后面的單詞。 我想避開整個方括號
也許可以解決問題,專注於你想要刪除的內容,而不是你想要保留的內容。 例如,這將匹配括號和任一側的空格,並替換為單個空格:
// Hello there How are you
var output = Regex.Replace("Hello there [Gesture : 2.5] How are you", @" \[.+\] ", " ");
如果需要,您可以使用稍微復雜的版本來處理方括號,不一定被空格包圍,例如在輸入字符串的開頭或結尾處:
var output = Regex.Replace(
"Hello there How are you [Gesture : 2.5]", // input string
@"[^\w]{0,1}\[.+\]([^\w]){0,1}", // our pattern to match the brackets and what's in between them
"$1"); // replace with the first capture group - in this case the character that comes after
如果你想,你可以使用Replace
的重載, Replace
MatchEvaluator
委托來更好地控制它在字符串中的替換方式以及取決於你的需求。
假設您希望括號前后的片段作為集合中的單獨條目:
Regex.Split(avatarVM.AvatarText, @"\[[^\]]+\]");
如果字符串中有多個括號內的片段,這也可以工作。 你可能想要.Trim()
每個條目。
var output = Regex.Replace("Hello there [Gesture : 2.5] How are you", @"\[.*?\] ", string.Empty);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.