extracting subsring from string using regular expression

时间:2021-10-25 13:05:22

I have a string like this

我有这样的字符串

ha regular{{patou0383838}}but if{{coffee}}i love {{tomato}}

I need a regular expression in c# that will help me to extract all text starting with {{ and ending with }}. So for instance in the example above, I should be able to have a group of 3 sub strings

我需要在c#中使用正则表达式来帮助我提取以{{和以}结尾}开头的所有文本。因此,例如在上面的示例中,我应该能够拥有一组3个子字符串

{{patou0383838}}
{{coffee}}
{{tomato}}

I tried various examples that I found on the web but they did not solve my problem.

我尝试了我在网上找到的各种例子,但他们没有解决我的问题。

3 个解决方案

#1


1  

You may try like this:

你可以尝试这样:

\{{.*?\}}

or

\{\{.*?\}\}

#2


0  

{ and } are special characters in regexes, so they need to be escaped. Also, since you could have more than one match in one line, you need to do a non-greedy match. The pattern will be something like

{和}是正则表达式中的特殊字符,因此需要进行转义。此外,由于您可以在一行中有多个匹配,因此您需要进行非贪婪的匹配。模式将是这样的

string pattern = @"(\{\{.*?\}\})"

The parenthesis are what are captured, including the {{ and }}

括号是捕获的内容,包括{{和}}

#3


0  

If your tokens are sure to be never nested like {{token {{1}}}} you can use

如果您的令牌肯定不会像{{token {{1}}}}那样嵌套,那么您可以使用

\{\{([^}]+)\}\}

The text enclosed within the braces is captured as group 1. For example, for a match like {{coffee}} the group one would hold coffee.

大括号内的文本被捕获为组1.例如,对于像{{coffee}}这样的匹配,组合将持有咖啡。


Although braces {} are used to specify ranges in a regex like {m,n} they aren't treated as special characters when included otherwise. So, we can simplify the regex by not escaping them as

{{([^}]+)}}

#1


1  

You may try like this:

你可以尝试这样:

\{{.*?\}}

or

\{\{.*?\}\}

#2


0  

{ and } are special characters in regexes, so they need to be escaped. Also, since you could have more than one match in one line, you need to do a non-greedy match. The pattern will be something like

{和}是正则表达式中的特殊字符,因此需要进行转义。此外,由于您可以在一行中有多个匹配,因此您需要进行非贪婪的匹配。模式将是这样的

string pattern = @"(\{\{.*?\}\})"

The parenthesis are what are captured, including the {{ and }}

括号是捕获的内容,包括{{和}}

#3


0  

If your tokens are sure to be never nested like {{token {{1}}}} you can use

如果您的令牌肯定不会像{{token {{1}}}}那样嵌套,那么您可以使用

\{\{([^}]+)\}\}

The text enclosed within the braces is captured as group 1. For example, for a match like {{coffee}} the group one would hold coffee.

大括号内的文本被捕获为组1.例如,对于像{{coffee}}这样的匹配,组合将持有咖啡。


Although braces {} are used to specify ranges in a regex like {m,n} they aren't treated as special characters when included otherwise. So, we can simplify the regex by not escaping them as

{{([^}]+)}}