Regex greedy issue (C #)

I have an input line like "=== text === and === text ===", and I want to replace the wiki syntax with the corresponding html tag.

input:

===text=== and ===text=== 

desired conclusion:

 <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 not greedy.

Thanks and kindly. Danny

+6
c # regex regex-greedy greedy
source share
5 answers

Add a question mark to your regular expression: === (. +?) ===

A better alternative would be to have a regular expression of the following form: === ([^ \ =] +) ===. See this guide for the dot symbol for an explanation of using the dot sparingly. When testing my supplied regex it's ok. 50% faster than your regular expression.

+13
source share

To make Regex not greedy, you use?

So, the expression "=== (. +?) ===" will have two matches for you - so you have to generate <h1>text</h1> and <h1>text</h1>

+3
source share

Just dd a ? may be?

 ===.+?=== 
0
source share

I will add one more option: ===((?:(?!===).)*)=== (stop catching any character when meeting === ) ... Oh ... and for the problem . proposed by WiseGuyEh, I suggest RegexOptions.SingleLine, so what . even matches a new line.

0
source share

And only for information, if others have the same problem, I had - to avoid matching also ====Text==== instead of ===Text=== I expanded the template as follows: (?<!=)===([^=]+)===(?!=)

0
source share

All Articles