编辑:一个字符串丢失了它的(
...... 8(抱歉浪费你的时间。
我有以下格式的字符串列表:
"Some Text (1234-567890)"
我试图在 周围使用string.Split
或Regex.Split
拆分它(
,然后从第一个元素中拉出前面的文本,并从第二个元素中拉出数字文本。
前任:
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)"
相反,我得到的是,无论我使用string.Split
还是Regex.Split
,我都会得到这个,是一个包含单个值而没有(
.
前任:
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
如果我使用Regex.Split
. 前任:
string[] myValues = Regex.Split(myText, "\\(");
如果我尝试将其放入一个新项目中,它会按我的预期工作。两者之间的唯一区别是我正在填充List<string>
使用 Excel 互操作。我不明白为什么会有所作为。
我的实际代码如下所示:
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
使用互操作范围函数从 Excel 工作表中读取值并将其转换为string
.