简体   繁体   English

Regex.Split和string.Split无法正常工作

[英]Regex.Split and string.Split not working as expected

I am attempting to split strings using '?' 我正在尝试使用'?'分割字符串 as the delimiter. 作为分隔符。 My code reads data from a CSV file, and certain symbols (like fractions) are not recognized by C#, so I am trying to replace them with a relevant piece of data (bond coupon in this case). 我的代码从CSV文件中读取数据,并且某些符号(如分数)无法被C#识别,因此我尝试将它们替换为相关数据(在这种情况下为bond coupon)。 I have print statements in the following code (which is embedded in a loop with index variable i) to test the output: 我在以下代码(包含在具有索引变量i的循环中)中具有打印语句以测试输出:

string[] l = lines[i][1].Split('?');               
//string[] l = Regex.Split(lines[i][1], @"\?");

System.Console.WriteLine("L IS " + l.Length.ToString() + " LONG");
for (int j = 0; j < l.Length; j++)
    System.Console.WriteLine("L["+ j.ToString() + "] IS " + l[j]);

if (l.Length > 1)
{
    double cpn = Convert.ToDouble(lines[i][12]);
    string couponFrac = (cpn - Math.Floor(cpn)).ToString().Remove(0,1);
    lines[i][1] = l[0].Remove(l[0].Length-1) + couponFrac + l[1]; // Recombine, replacing '?' with CPN
}

The issue is that both split methods ( string.Split() and Regex.Split() ) produce inconsistent results with some of the string elements in lines splitting correctly and the others not splitting at all (and thus the question mark is still in the string). 问题在于,两个拆分方法( string.Split()Regex.Split() )均产生不一致的结果,其中行中的某些字符串元素正确拆分,而其他字符串根本不拆分(因此,问号仍在串)。

Any thoughts? 有什么想法吗? I've looked at similar posts on split methods and they haven't been too helpful. 我看过有关拆分方法的类似文章,但它们并没有太大帮助。

I didn't have any trouble parsing the following. 解析以下内容没有任何麻烦。

var qsv = "now?is?the?time";
var keywords = qsv.Split('?');
keywords.Dump();

screenshot of code and output... 屏幕截图的代码和输出...

在此处输入图片说明

UPDATE: There doesn't appear to be any problem with Split . 更新: Split似乎没有任何问题。 There is a problem somewhere else because in this small scale test it works just fine. 在其他地方存在一个问题,因为在此小规模测试中它可以正常工作。 I would suggest you use LinqPad to test out these kinds of scenarios small scale. 我建议您使用LinqPad进行小规模测试。

var qsv = "TII 0 ? 04/15/15";
var keywords = qsv.Split('?');
keywords.Dump();

qsv = "TII 0 ? 01/15/22";
keywords = qsv.Split('?');
keywords.Dump();

New updated output: 新的更新输出:

在此处输入图片说明

I had no problem using String.Split. 使用String.Split我没有问题。 Could you post your input and output? 您可以发布您的输入和输出吗? If at all you could probably use String.Replace to replace your desired '?' 如果完全可以,您可以使用String.Replace替换所需的“?” with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect. 使用字符串中未出现的字符,然后对该字符使用String.Split拆分结果字符串以达到相同的效果。 (just a try) (尝试一下)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM