使用定界符分割字符串,但将定界符保留在C#中的结果中 [英] Split a string with delimiters but keep the delimiters in the result in C#
本文介绍了使用定界符分割字符串,但将定界符保留在C#中的结果中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用定界符分割字符串,但将定界符保留在结果中。
I would like to split a string with delimiters but keep the delimiters in the result.
我如何在C#中做到这一点?
How would I do this in C#?
推荐答案
如果希望分隔符成为其自己的分隔符,则可以使用 Regex.Split 例如:
If you want the delimiter to be its "own split", you can use Regex.Split e.g.:
string input = "plum-pear";
string pattern = "(-)";
string[] substrings = Regex.Split(input, pattern); // Split on hyphens
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
// The method writes the following to the console:
// 'plum'
// '-'
// 'pear'
因此,如果要拆分数学公式,可以使用以下正则表达式
So if you are looking for splitting a mathematical formula, you can use the following Regex
@"([*()\^\/]|(?<!E)[\+\-])"
这将确保您还可以使用常量,例如1E-02,并避免将它们拆分为1E,-和02
This will ensure you can also use constants like 1E-02 and avoid having them split into 1E, - and 02
因此:
Regex.Split("10E-02*x+sin(x)^2", @"([*()\^\/]|(?<!E)[\+\-])")
收益率:
-
10E-02
-
*
-
x
-
+
-
sin
-
(
-
x
-
)
-
^
-
2
10E-02
*
x
+
sin
(
x
)
^
2
这篇关于使用定界符分割字符串,但将定界符保留在C#中的结果中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文