如何通过多个定界符分割字符串并保留定界符? [英] how can i split a string by multiple delimiters and keep the delimiters?

查看:63
本文介绍了如何通过多个定界符分割字符串并保留定界符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有此字符串 "abc({" .
现在,我想用 (" 分隔符将其分割,我知道我可以为此使用String.split.
但是有没有一种方法可以分割这个符号,但又不会丢失呢?就像我使用split一样,我会得到这个 string [] = {"abc","{"} ,而我想要 {"abc",(","{"} .
还可以使用多个定界符来做到这一点吗?

i have for exemple this string "abc({".
now, i want to split it by the "(" delimiter, and i know i can use String.split for that.
but is there a way i can split if by this symbol but not loss it? like if i used split i would have gotten this string[] = { "abc" , "{" } and i want { "abc" , "(" , "{" }.
also is there a way to do this with multiple delimiters?

推荐答案

使用 Regex.Split (带有捕获组随附的模式).

Use Regex.Split with a pattern enclosed with a capturing group.

如果在 Regex.Split 表达式中使用捕获括号,则任何捕获的文本都将包含在结果字符串数组中.

If capturing parentheses are used in a Regex.Split expression, any captured text is included in the resulting string array.

请参见 C#演示:

var s = "abc({";
var results = Regex.Split(s, @"(\()")
    .Where(m=>!string.IsNullOrEmpty(m))
    .ToList();
Console.WriteLine(string.Join(", ", results));
// => abc, (, {

(\()正则表达式匹配并将()符号捕获到捕获组1中,因此捕获的部分也将输出到结果字符串列表中.

The (\() regex matches and captures ( symbol into Capturing group 1, and thus the captured part is also output in the resulting string list.

这篇关于如何通过多个定界符分割字符串并保留定界符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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