[英]Remove last occurrence of a string in a string
我有一個自然的字符串
我想要的是從字符串中刪除last()事件。 也就是說,如果字符串是 - RTT(50),那么我只想返回RTT。 如果是RTT(A)(50),我想要RTT(A)返回等。
我該如何實現這一目標? 我目前使用子串方法,無論如何都會取出任何出現的()。 我想過使用:
Regex.Matches(node.Text, "( )").Count
要計算出現的次數,所以我做了類似下面的事情。
if(Regex.Matches(node.Text, "( )").Count > 1)
//value = node.Text.Remove(Regex.//Substring(1, node.Text.IndexOf(" ("));
else
value = node.Text.Substring(0, node.Text.IndexOf(" ("));
else部分會做我想要的。 但是,如何刪除if部分中的最后一個匹配項是我被卡住的地方。
String.LastIndexOf
方法執行您所需的操作 - 返回char或字符串的最后一個索引。
如果您確定每個字符串至少有一組括號:
var result = node.Text.Substring(0, node.Text.LastIndexOf("("));
否則,您可以測試LastIndexOf
的結果:
var lastParenSet = node.Text.LastIndexOf("(");
var result =
node.Text.Substring(0, lastParenSet > -1 ? lastParenSet : node.Text.Count());
這應該做你想要的:
your_string = your_string.Remove(your_string.LastIndexOf(string_to_remove));
就這么簡單。
有幾種不同的選擇需要考慮。
獲取(
字符的最后一個索引並將子字符串帶到該索引。此方法的缺點是需要額外的最后一次索引檢查)
以確保格式正確並且它是一對具有右括號的在左括號后(我沒有在下面的代碼中執行此檢查)。
var index = input.LastIndexOf('(');
if (index >= 0)
{
var result = input.Substring(0, index);
Console.WriteLine(result);
}
通過使用RegexOptions.RightToLeft
我們可以獲取一對括號的最后一個索引。
var pattern = @"\(.+?\)";
var match = Regex.Match(input, pattern, RegexOptions.RightToLeft);
if (match.Success)
{
var result = input.Substring(0, match.Index);
Console.WriteLine(result);
}
else
{
Console.WriteLine(input);
}
如果你總是希望最后的括號有數字內容,類似於你的示例值,其中(50)
被刪除,我們可以使用匹配括號內任何數字的模式。
var patternNumeric = @"\(\d+\)";
var result = Regex.Replace(input, patternNumeric, "");
Console.WriteLine(result);
這很簡單。 您可以輕松實現這樣的目標:
string a = RTT(50);
string res = a.substring(0,a.LastIndexOf(“(”))
作為延伸:
namespace CustomExtensions
{
public static class StringExtension
{
public static string ReplaceLastOf(this string str, string fromStr, string toStr)
{
int lastIndexOf = str.LastIndexOf(fromStr);
if (lastIndexOf < 0)
return str;
string leading = str.Substring(0, lastIndexOf);
int charsToEnd = str.Length - (lastIndexOf + fromStr.Length);
string trailing = str.Substring(lastIndexOf+fromStr.Length, charsToEnd);
return leading + toStr + trailing;
}
}
}
使用:
string myFavColor = "My favourite color is blue";
string newFavColor = myFavColor.ReplaceLastOf("blue", "red");
嘗試一下這個功能:
public static string ReplaceLastOccurrence(string source, string find, string replace)
{
int place = source.LastIndexOf(find);
return source.Remove(place, find.Length).Insert(place, replace);
}
它將刪除最后一次出現的字符串字符串並替換為另一個字符串,並使用:
string result = ReplaceLastOccurrence(value, "(", string.Empty);
在這種情況下,您會找到(
字符串在value
字符串中,並替換(
到string.Empty
。它也可以用於替換另一個信息)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.