如何读取具有混合字符串和整数且没有分隔值的文本文件 [英] how to read a text file with mixed string and integer and without separated value

查看:73
本文介绍了如何读取具有混合字符串和整数且没有分隔值的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个混合字符串和整数的文本文件,如下所示:

X12 Y0.4 Z8

X4.5 Y231 Z32.4

Y0.4 Z8

X54 Y5.11 Z9

Y78 Z68











我在文本文件中只有X,Y,Z

我总是有Y,Z但可能没有X

我在我的程序中定义了双x,y,z,

我怎么能读取每行中的整数并将其值保存为x,y,z?

我应该使用该模式吗?我怎么能为这个文本文件写一个模式?

请帮帮我

hi
I have a text file with mixed string and integer like this:
X12 Y0.4 Z8
X4.5 Y231 Z32.4
Y0.4 Z8
X54 Y5.11 Z9
Y78 Z68
.
.
.


I have only X,Y,Z in text file
I Always have Y,Z but may not have X
I defined double x,y,z in my program,
how i can read integers in each line and save their values as x,y,z?
Should I use the pattern? how i can write a pattern for this text file?
please help me

推荐答案

就个人而言,我会使用正则表达式:

Personally, I would use a regex:
(?<key>[a-zA-Z]+)(?<value>(\d*\.\d+)|(\d+))

应该这样做。





编码的HTML - 该死的! - OriginalGriff [/ edit]





OP的长期更新



你可以,但维护起来非常糟糕。

你知道你可以从正则表达式中获得多个匹配吗?

试试这个:

Should do it.


[edit]Encoded HTML - damnit! - OriginalGriff[/edit]


Long update from OP

You could, but it''s pretty horrible to maintain.
Did you know that you can get more than one Match from a regex?
Try this:

Regex regex = new Regex(@"(?<key>[a-zA-Z]+)(?<value>(\d*\.\d+)|(\d+))");
float x = 0.0F, y = x, z = x;
string[] lines = File.ReadAllLines(pathToFile);
foreach (string line in lines)
    {
    foreach (Match m in regex.Matches(line))
        {
        string key = m.Groups["key"].Value;
        string val = m.Groups["value"].Value;
        float f;
        if (float.TryParse(val, out f))
            {
            switch (key)
                {
                case "X": x = f; break;
                case "Y": y = f; break;
                case "Z": z = f; break;
                }
            }
        }
    Console.Write("{0},{1},{2}", x, y, z);
    }


你有X12 Y0.4 Z8这样的模式,在这种情况下我可以看到它们之间的空格字符。如果是这种情况,那么您可以使用空格字符拆分字符串。正如您所说的,X可能存在也可能不存在,并且可以根据结果数组所包含的项目数来确定。然后,您可以通过相应地替换X,Y或Z来获得相应的值。



如果两者之间不存在空间......

在这种情况下,您还可以检查行中是否存在X并使用子字符串来获取数字部分。
Do you have pattern like X12 Y0.4 Z8, in this case I can see a space character in between. If that is the case then you can just split the string with space character. As you said X may or may not be present and that can be determined on the basis of number of items the resultant array holds. You can then get the respective value by replacing X,Y or Z accordingly.

If space is not present in between...
In this case also you can check if X exists in the line and use substring to get numeric part.


这篇关于如何读取具有混合字符串和整数且没有分隔值的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆