C#正则表达式拆分两个可变词 [英] C# Regex split two variable words

查看:76
本文介绍了C#正则表达式拆分两个可变词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用正则表达式拆分文本文件的两个部分时遇到问题.基本上,将显示一个班级的名称,但是房间号之后将是一个空格.我不能保证房间的名称,否则我会分开讨论.

I'm having an issue splitting up two parts of a text file with regex. Basically, a name of a class will appear, but then the room number will come one white space after it. I am not guaranteed the name of the room, otherwise I would split on that.

为了说明这一点,可以很好地拆分:

To illustrate, this splits perfectly fine:

WEB SITE DEVELOPMENT II     NKM 104

由于空白,它会分裂,所以在我的string []数组中,它看起来像:

It will split because of the white spaces, so in my string[] array it looks like:

0 - WEB SITE DEVELOPMENT II
1 - KNM 104

这是我所需要的.问题出在诸如此类的条目上:

Which is what I need. The problem lies in entries such as these:

PERSONAL COMPUTER APPLICATI NKM 106
PORTFOLIO DES & PROF PRACTI LCN 104

显示为:

0 - PERSONAL COMPUTER APPLICATI NKM 104
1 - PORTFOLIO DES & PROF PRACTI LCN 104

当我需要时:

0 - PERSONAL COMPUTER APPLICATI
1 - KNM 104
2 - PORTFOLIO DES & PROF PRACTI 
3 - LCN 104

在这样的情况下,从何处开始一些正则表达式的任何想法?我知道我可以保证房间号始终是"XYZ 012"的形式,但是问题是它出现在班级名称之后.以前,我可以轻松地就此进行讨论.感谢您的帮助.

Any ideas on where to start on some regex in a situation like this? I know I am guaranteed the room number will always be the "XYZ 012" form, but the problem is it comes after the name of the class. It was before, I could easily just split on that. Any help is appreciated.

推荐答案

此处不需要正则表达式...

No need for regexes here...

var firstPart = line.Substring(0, line.Length - 8);
var lastPart = line.Substring(line.Length - 7);

...以及完整的示例:

... and the complete example:

var data = lines.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                .SelectMany(line => new[] {line.Substring(0, line.Length - 8), line.Substring(line.Length - 7)})
                .Select((part, i) => string.Format("{0} - {1}", i, part));

var asString = string.Join(Environment.NewLine, data);

这篇关于C#正则表达式拆分两个可变词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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