1

编辑:一个字符串丢失了它的(...... 8(抱歉浪费你的时间。

我有以下格式的字符串列表:

"Some Text (1234-567890)"

我试图在 周围使用string.SplitRegex.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.

4

5 回答 5

1

您显示的代码按预期工作。获得该结果的唯一方法是字符串不包含任何起始括号,例如 contains"Some Text 1234-567890)"和 not "Some Text (1234-567890)"

也有可能你有一些不寻常的字符,在一个环境中看起来像一个起始括号,但在另一个环境中是一个不可打印的字符。

当您从 Exfel 表中获取字符串时,您应该检查它们实际包含的内容。

于 2012-08-09T23:52:08.313 回答
0
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(")","");

您需要转义左括号。它对正则表达式引擎有特殊的意义。

于 2012-08-09T23:38:00.723 回答
0

此代码应该可以工作:

string[] myValues = myText.Split(new string[] { "(" }, StringSplitOptions.None);
于 2012-08-09T23:47:42.980 回答
0

数据格式不正确。一行是这样的:

"Some Text 1234-567890)"

所以 Split 方法只返回那个字符串。

于 2012-08-09T23:49:43.590 回答
0

如果您想这样做,这里是使用您的代码的解决方案,我刚刚添加了一个新行 myValues[1]= myValues[1].Replace(")",""); 这消除了您看到 原始代码可以消除“(”但“(”和“)”之间存在差异的烦人的“)”字符

这是一个更好的例子,传递参数,用“,”分隔

string myText = "Some Text (1234-567890)";
string[] myValues = myText.Split('(',')');
string first = myValues[0]; // should hold "Some Text "
string second = myValues[1]; 
于 2012-08-09T23:53:20.677 回答