EDIT: A single string was missing its (… 8( Sorry for wasting your time.
I have a list of strings of the following format:
"Some Text (1234-567890)"
I am trying to use string.Split or Regex.Split to split this around the (, and then pull the preceding text from the first element, and the number text off the second element.
Ex:
string myText = "Some Text (1234-567890)";
string[] myValues = myText.Split('(');
string first = myValues[0]; // should hold "Some Text "
string second = myValues[1]; // should hold "1234-567890)"
Instead what I’m getting, and I get this whether I use string.Split or Regex.Split, is an array containing a single value without the (.
Ex:
string myText = "Some Text (1234-567890)";
string[] myValues = myText.Split('(');
string first = myValues[0]; // has "Some Text 1234-567890)"
string second = myValues[1]; // exception; there is no second value
This also happens if I use Regex.Split. Ex:
string[] myValues = Regex.Split(myText, "\\(");
If I try putting this into a fresh project, it works as I expect. The only difference between the two is that I’m populating the List<string> using Excel interop. I don’t see why that would make a difference.
My actual code looks like this:
const int LOCATION_START = 2;
const int LOCATION_END = 39;
List<string> locationStrings = new List<string>();
for (int row = LOCATION_START + 1; row <= LOCATION_END; row++)
locationStrings.Add(pExcel.ActiveSheet.ReadValue<string>(row));
List<Tuple<string, string>> locations = new List<Tuple<string, string>>();
foreach (string locationString in locationStrings)
{
string[] values = Regex.Split(locationString, "\\(");
locations.Add(Tuple.Create(values[0].Trim(), values[1].Substring(0, 11)));
// ^ this line throws an exception, because there is only one value, not two
}
Excel.ActiveSheet.ReadValue uses the interop Range function to read a value from an Excel sheet and casts it to a string.
The code that you show works as expected. The only way to get that result is that the string doesn’t contain any starting parenthesis, e.g. contains
"Some Text 1234-567890)"and not"Some Text (1234-567890)".It’s also possible that you have some unusal character that looks like a starting parenthesis in one environment, but is an unprintable character in another.
You should check what your strings actually contain when you get them from the Exfel sheet.