简体   繁体   English

从字符串中删除子字符串

[英]Remove Substring from string

I have a string: 我有一个字符串:

string valueA = "Free Chips (Save $43 / month)";

Now I want to retrieve string that occurs before (Save , ie I want Free Chips . How can I achieve this? 现在,我想检索之前发生的字符串(Save ,即我想要Free Chips 。如何实现?

string valueB = valueA.Replace(); 

Use Substring and IndexOf 使用SubstringIndexOf

string valueB = valueA.Substring(0, valueA.IndexOf("(Save", StringComparison.Ordinal))
                      .Trim();

You can use a regex with positive lookahead : 您可以使用正瞻性 正则表达式

.*?(?=\s*\(Save)

The full code: 完整代码:

using System.Text.RegularExpressions;

string query = "Free Chips (Save $43 / month)";

// ...

Regex r = new Regex(@".*?(?=\s*\(Save)");

Match m = r.Match(query);
if(m.Success) {
    string result = m.ToString(); // result = "Free Chips"
}

m.Success is false if "(Save" is not part of the string. 如果"(Save"不是字符串的一部分,则m.Successfalse

One of the ways is regex (of course for such a simple string it could be an little overhead): 一种方法是正则表达式(当然,对于这样一个简单的字符串可能会有点开销):

var regex = new Regex("(.*)\(Save");
// (.*) - match anything and group it
// \(Save - match "(Save" literally
var regexMatch = regex.Match(valueA);
if (regexMatch.Success)
{
    var valueB = regex.Match(valueA).Groups[1].Value;
    //and so on
}
string valueA = "Free Chips (Save $43 / month)";
string valueB = valueA.Substring(0, valueA.IndexOf(" (Save"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM