I've a input string like "===text=== and ===text===" and I want to replace wiki syntax with the corresponding html tag.
input:
===text=== and ===text===
desirable output:
<h1>text</h2> and <h1>text</h2>
but with the following code I get this output:
var regex = new Regex("---(.+)---");
var output = regex.Replace("===text=== and ===text===", "<h1>$1</h1>");
<h1>text=== and ===text</h1>
I know the problem is that my regex matches greedy. But how to make them non greedy.
Thank you and kind regards. Danny
Add the question mark to your regex: ===(.+?)===
A better alternative would be to have a regex of the following form: ===([^\\=]+)===. See this guide on the dot character for an explanation of using the dot sparingly. When benchmarking my supplied regex, it is approx. 50% faster than your regex.
To make a Regex not greedy you use ?
So the expression "===(.+?)===" would have two matches for you - so should allow you to generate <h1>text</h1>
and <h1>text</h1>
Simply dd a ?
maybe?
===.+?===
I'll add another variant: ===((?:(?!===).)*)===
(stop catching any character when you encounter ===
)... Oh... and for the .
problem suggested by WiseGuyEh, I suggest RegexOptions.SingleLine, so that the .
match even the newline.
只是为了信息,如果其他人有相同的问题,那么我 - 避免匹配也====Text====
而不是===Text===
我已经扩展了这样的模式: (?<!=)===([^=]+)===(?!=)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.