用分隔符拆分字符串,但将分隔符保留在 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
这篇关于用分隔符拆分字符串,但将分隔符保留在 C# 中的结果中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文