[英]How to match the first occurrence of a character and split it
我有一個文本文件,我想從中將Keys
和Values
存儲在String
數組中。
在這種情況下, Key
類似於“輸入文件”, Value
是“ 'D:\\myfile.wav' ”。 我正在按**:**
字符拆分文本文件行。 但是,我只想將拆分限制為僅第一次出現**:**
。
這是我的代碼:
輸入文件:'D:\\myfile.wav'
持續時間 : 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 是一個靜態成員,以避免在每次使用時編譯它。 ?
在表達式中是強制惰性行為(貪婪是默認值)並匹配第一個:
。
在您發表評論后,我已經更新了代碼和小提琴。 我想這就是你的意思:
鍵:任何字母、下划線和空格組合(無數字) 值:任何鍵和值之間的分隔符::
基本上,您不想拆分整個字符串,而是在遇到第一個 ':' 字符加一個符號(':' 本身)之前跳過所有內容。
var data = line.Substring(line.IndexOf(':') + 1);
或者,如果您真的想要 Split 解決方案:
var data = string.Join(":", line.Split(':').Skip(1));
在這里,我們首先將字符串拆分為數組,然后跳過一個元素(我們試圖擺脫的元素),最后在數組中的元素之間構造一個帶有 ':' 的新字符串。
這是使用正則表達式執行此操作的一種方法(代碼中的注釋):
string[] lines = {@"Input File : 'D:\myfile.wav'", @"Duration: 00:00:18.57"};
Regex regex = new Regex("^[^:]+");
Dictionary<string, string> dict = new Dictionary<string, string>();
for (int i = 0; i < lines.Length; i++)
{
// match in the string will be everything before first :,
// then we replace match with empty string and remove first
// character which will be :, and that will be the value
string key = regex.Match(lines[i]).Value.Trim();
string value = regex.Replace(lines[i], "").Remove(0, 1).Trim();
dict.Add(key, value);
}
它使用模式^[^:]+
,這是一種否定類技術來匹配所有內容,除非指定字符。
通過這種方式,您可以讀取文本文件的每一行。 你用 Key = 填充 json 直到 ":" Value= From ":"
Dictionary<string, string> yourDictionary = new Dictionary<string, string>();
string pathF = "C:\\fich.txt";
StreamReader file = new StreamReader(pathF, Encoding.Default);
string step = "";
List<string> stream = new List<string>();
while ((step = file.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(step))
{
yourDictionary.Add(step.Substring(0, step.IndexOf(':')), step.Substring(step.IndexOf(':') + 1));
}
}
之后您需要將 put 信息讀取到String Line
,執行此操作。
String Key = Line.Split( ':' )[0];
String Value = Text.Substring( Key.Length + 1, Text.Length - Property.Length - 1 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.