【问题标题】:Remove only the first match in string仅删除字符串中的第一个匹配项
【发布时间】:2016-10-07 09:55:28
【问题描述】:

从一个字符串中,检查它是否以值“startsWithCorrectId”开头...如果它确实从一开始就删除了该值。问题是如果在字符串中再次找到此值,它也会将其删除。我意识到这就是 .replace 所做的......但是有没有类似 .startsWith 到 RemoveAtStart 的东西?

string startsWithCorrectId = largeIconID.ToString();
//startsWithCorrectId will be '1'

string fullImageName = file.Replace("_thumb", "");
//fullImageName will be "1red-number-1.jpg"

//file will be '1red-number-1_thumb.jpg'
if(file.StartsWith(startsWithCorrectId))
{
    fullImageName = fullImageName.Replace(startsWithCorrectId, "");
    //so yes this is true but instead of replacing the first instance of '1'..it removes them both
}

我真正想要的是让 '1red-number-1.jpg' 变成 'red-number-1.jpg'....而不是 'red-number-.jpg'.. 替换 ' 的所有实例startsWithCorrectId' 我只想替换第一个实例

【问题讨论】:

  • 可以使用IndexOf和Substring,也可以使用Regex.Replace
  • 只有在开头,还是第一次出现?
  • 对您收到的 4 个答案有任何反馈...?
  • 这方面有什么更新吗?

标签: c#


【解决方案1】:

一种解决方案是使用Regex.Replace():

fullImageName = Regex.Replace(fullImageName, "^" + startsWithCorrectId, "");

如果 startsWithCorrectId 在字符串的开头,这将删除它

【讨论】:

  • 这并不是真正的要求,但在我的情况下它就像一个魅力(在我的上下文中,第一次出现总是在第一个位置)。
【解决方案2】:
if(file.StartsWith(startsWithCorrectId))
{
    fullImageName = fullImageName.SubString(startsWithCorrectId.Length);    
}

【讨论】:

  • 为了清楚起见,我会使用startsWithCorrectId.Length。
【解决方案3】:

如果我没有正确地理解你,你需要从正确的Id.Length位置开始获取一个字符串

 if(fullImageName .StartsWith(startsWithCorrectId))
     fullImageName = fullImageName .Substring(startsWithCorrectId.Length);

如果你喜欢扩展:

public static class StringExtensions{

   public static string RemoveFirstOccuranceIfMatches(this string content, string firstOccuranceValue){
        if(content.StartsWith(firstOccuranceValue))
            return content.Substring(firstOccuranceValue.Length);
        return content;
   }
}


//...
fullImageName = fullImageName.RemoveFirstOccuranceIfMatches(startsWithCorrectId);

【讨论】:

  • @Andrew 我在他的示例中没有看到 correctId 变量
  • 我也不是,但我认为您在回复中使用了它。 :)
【解决方案4】:

您可以使用正则表达式来执行此操作,您可以在其中对字符串从开头开始的要求进行编码:

var regex = "^" + Regex.Escape(startsWithCorrectId);
// Replace the ID at the start. If it doesn't exist, nothing will change in the string.
fullImageName = Regex.Replace(fullImageName, regex, "");

另一种选择是使用子字符串,而不是替换操作。你已经知道它在字符串的开头,你可以从它之后的子字符串开始:

fullImageName = fullImageName.Substring(startsWithCorrectId.Length);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 2015-01-22
    • 2011-09-25
    相关资源
    最近更新 更多