简体   繁体   English

正则表达式替换[*

[英]Regular expression replace [*

How to replace the string using regular expression for the following pattern 如何使用正则表达式替换以下模式的字符串

[*1. [* 1。 Introduction*] 介绍*]

to

  1. Introduction 介绍

i've replaced it simply by 我已经简单地替换为

string s="[*1. Introduction*]";
s.Replace("[*", string.Empty).Replace("*]", string.Empty);

is it any equivalent for this using regular expression in c#. 在c#中使用正则表达式是否等效?

Yes.. 是..

 Regex.Replace(s,"^\\[\\*|\\*\\]$", string.Empty);

Though I recommend you to stick with String's Replace method.. 虽然我建议您坚持使用String的Replace方法。

The advantage of using a regular expression for this, would be to assure that it wouldn't replace any [* or *] that would occur by themselves. 为此使用正则表达式的好处是确保它不会替换任何将自己出现的[**] The pattern can match the occurance of both. 该模式可以匹配两者的出现。

A limitation of using such a pattern would be that it can't handle nested occurances, eg "Some [*text [*with*] nested*] tags." 使用这种模式的局限性在于它无法处理嵌套的事件,例如"Some [*text [*with*] nested*] tags." .

Performance for using a regular expression compared to String.Replace would be about the same. String.Replace相比,使用正则表达式的性能大致相同。 There is some overhead when creating the regular expression, but you need to run through the string twice when you use String.Replace . 创建正则表达式时会有一些开销,但是在使用String.Replace时,您需要对字符串运行两次。

Using a regular expression would look like this: 使用正则表达式如下所示:

s = Regex.Replace(s, @"\[\*(.+)\*\]", "$1");

The parentheses in the pattern captures what's within the tags, and $1 in the replacement string uses what was captured to replace the entire tag. 模式中的括号捕获标记内的内容,替换字符串中的$1使用捕获的内容替换整个标记。

就像@BenRobinson所说的,顺便说一句,我不知道这件事:D

string s = " [*1. Introduction*] ".Trim(' ', '[', ']', '*');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM