如何匹配字符的第一个出现并将其拆分 [英] How to match the first occurrence of a character and split it
问题描述
我有一个文本文件,我想从中将 Keys
和 Values
存储在 String
数组中.
I have a text file from which I want to store Keys
and Values
in a String
array.
在这种情况下, Key
类似于"输入文件"并且 Value
是"'D:\ myfile.wav'".我用 **:**
字符分割文本文件行.但是,我只想将拆分限制为仅出现 **:**
.
In this case, Key
is something like "Input File" and the Value
is "'D:\myfile.wav'". I'm splitting the text file lines by **:**
character. However, I just want to restrict the split to only the first occurrence of **:**
.
这是我的代码:
输入文件:'D:\ myfile.wav'
Input File : 'D:\myfile.wav'
持续时间:00:00:18.57
Duration : 00:00:18.57
if (Regex.IsMatch(line, @"[^0-9\p{L}:_ ]+", RegexOptions.IgnoreCase))
{
string[] dataArray = line.Split(':');
}
推荐答案
使用正则表达式捕获
private static Regex _regex = new Regex(@"^([\p{L}_ ]+):?(.+)$");
....
Match match = _regex.Match(line);
if (match.Success)
{
string key = match.Groups[1].Captures[0].Value;
string value = match.Groups[2].Captures[0].Value;
}
regexp是静态成员,以避免每次使用时都对其进行编译.表达式中的?
是强制执行懒惰行为(默认为greedy)并匹配第一个:
.
The regexp is a static member to avoid compiling it for every usage. The ?
in the expression is to force lazy behavior (greedy is the default) and match the first :
.
在您发表评论后,我已经更新了代码并进行了改进.我认为这就是您的意思:
I've updated the code and fiddle after your comment. I think this is what you mean:
键:任意字母,下划线和空格组合(无数字)值:任何键和值之间的分隔符::
Key: Any letter, underscore and whitespace combination (no digits) Value: anything Separator between key and value: :
这篇关于如何匹配字符的第一个出现并将其拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!