Reputation: 1809
I have a string:
string valueA = "Free Chips (Save $43 / month)";
Now I want to retrieve string that occurs before (Save
, i.e I want Free Chips
. How can I achieve this?
string valueB = valueA.Replace();
Upvotes: 0
Views: 166
Reputation: 3373
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
}
Upvotes: 0
Reputation: 476557
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.
Upvotes: 1
Reputation: 328
string valueA = "Free Chips (Save $43 / month)";
string valueB = valueA.Substring(0, valueA.IndexOf(" (Save"));
Upvotes: 0
Reputation: 9365
Use Substring
and IndexOf
string valueB = valueA.Substring(0, valueA.IndexOf("(Save", StringComparison.Ordinal))
.Trim();
Upvotes: 1