![](/img/trans.png)
[英]C# Regex, match but not include the first character before matched string
[英]Regex to match last character in string - C#
如何刪除最后一個';' 一串?
如果在字符串末尾添加注釋,則需要返回“;” 評論之前。
范例 :
"line 1 //comment
line2;
extra text; //comment may also contain ;."
您沒有寫想要使用該字符的內容,因此我在這里為您提供了一個替換字符的解決方案:
string pattern = "(?<!//.*);(?=[^;]*(//|$))";
Console.WriteLine(Regex.Replace("line 1 //comment", pattern, "#"));
Console.WriteLine(Regex.Replace("line2;", pattern, "#"));
Console.WriteLine(Regex.Replace("extra; text; //comment may also contain ;.", pattern, "#"));
輸出:
line 1 //comment
line2#
extra; text# //comment may also contain ;.
正則表達式有點丑陋,但是這里是:
var str = @"line 1 //comment
line2; test;
extra text; //comment may also contain ;.";
var matches = Regex.Matches(str, @"^(?:(?<!//).)+(;)", RegexOptions.Multiline);
if (matches.Count > 0)
{
Console.WriteLine(matches[matches.Count - 1].Groups[1].Index);
}
我們得到每行最后一個分號的匹配項(沒有注釋),然后查看這些匹配項的最后一個。
我們必須逐行執行此操作,因為注釋適用於整行。
如果要單獨處理每一行(您的問題不是這樣,而是隱含的意思),那么請遍歷matches
而不是僅查看最后一行。
如果要用另一個字符替換每個分號,則可以執行以下操作:
const string replacement = "#";
var result = Regex.Replace(str, @"^((?:(?<!//).)+);", "$1" + replacement, RegexOptions.Multiline);
如果要完全刪除它,則只需:
var result = Regex.Replace(str, @"^((?:(?<!//).)+);", "$1", RegexOptions.Multiline);
如果只想刪除整個字符串中的最后一個分號,則可以只使用string.Remove
:
var matches = Regex.Matches(str, @"^(?:(?<!//).)+(;)", RegexOptions.Multiline);
if (matches.Count > 0)
{
str = str.Remove(matches[matches.Count - 1].Groups[1].Index, 1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.