如何提取字符串中的占位符 - C#

问题描述 投票:0回答:1

假设我有一个像这样的字符串: “我的名字是 <>,我在 <> 团队工作 作为 <>。”

如何提取 <> 以便最终得到一个列表:

我的名字是
<>
我在
工作 <>
团队 作为一个
<>
.

备注:

  • << and >>之间的内容可以是任何内容。换句话说,它们不是预定义的。
  • << and >> 字符之间可以有空格字符(如 <>)
  • 字符串可以包含换行符 和/或 但我希望它们被保留下来。

我想在C#中使用Regex,但没有成功。

c# regex
1个回答
0
投票

您可以使用正则表达式来平衡此SO帖子中的字符。调整后如下所示:

\<\<(?>\<\<(?<c>)|[^<>]+|\>\>(?<-c>))*(?(c)(?!))\>\>

它将数学平衡

<< .... >>
代币。

然后您可以使用

Regex.Matches
Regex.Split
来获取您想要的所有物品:

var regex = new Regex(@"\<\<(?>\<\<(?<c>)|[^<>]+|\>\>(?<-c>))*(?(c)(?!))\>\>");

var searchString = "My name is <<yourName>> and I am working in the <<Team Name>> team\n as a <<yourTitle>>.";

var matches = regex.Matches(searchString);

var parts = regex.Split(searchString);
© www.soinside.com 2019 - 2024. All rights reserved.