编辑:单个字符串缺少其(... 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, "\\(");如果我试着把它放到一个新的项目中,它会像我预期的那样工作。两者之间唯一的区别是我使用Excel interop填充List<string>。我不明白为什么这会有什么不同。
我的实际代码如下所示:
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。
发布于 2012-08-10 07:52:08
您显示的代码可以按预期工作。获得该结果的唯一方法是字符串不包含任何起始括号,例如包含"Some Text 1234-567890)"而不包含"Some Text (1234-567890)"。
也有可能您有一些不一致的字符,在一个环境中看起来像一个开始括号,但在另一个环境中却是一个无法打印的字符。
从Exfel工作表中获取字符串时,应检查字符串实际包含的内容。
发布于 2012-08-10 07:38:01
string Source = "Some Text (1234-567890)";
string[] Splitted = Regex.Split(Source, @"\(");
foreach (string Item in Splitted)
Console.WriteLine(Item.Replace(")",""); //Use replace if you want to remove the closing bracket.
//Map the values
string First = Splitted[0];
string Second = Splitted[1].Replace(")","");你需要摆脱开方括号。它对regex引擎有特殊的意义。
发布于 2012-08-10 07:47:43
下面的代码应该可以工作:
string[] myValues = myText.Split(new string[] { "(" }, StringSplitOptions.None);https://stackoverflow.com/questions/11893457
复制相似问题