Regex replaces any number of matches at the beginning of a line

I have text with this structure:

1. Text1 2. Text 2. It has a number with a dot. 3. 1. Text31 

I want to get this text:

 # Text1 # Text 2. It has a number with a dot. (notice that this number did not get replaced) ## Text31 

I tried to do the following but not working

 var pattern = @"^(\s*\d+\.\s*)+"; var replaced = Regex.Replace(str, pattern, "#", RegexOptions.Multiline); 

Basically, it should start matching at the beginning of each line and replace each matching group with the # character. Currently, if more than one group is matched, everything is replaced with a single # character. I am using the template, probably the wrong one, can anyone come up with a solution?

+5
source share
2 answers

you can use

 (?:\G|^)\s*\d+\. 

It matches the beginning of a line or the end of a previous successful match or the beginning of a line, and then zero or more spaces, one or more digits and a period.

More details

  • (?:\G|^) - beginning of line or end of previous match ( \G ) or beginning of line ( ^ )
  • \s* - zero or more spaces, if you want to coincide with horizontal spaces, to avoid overflow with the next lie (s), replace with [\s-[\r\n]]* or [\p{Zs}\t]* )
  • \d+ - one or more digits (to match only ASCII digits, replace with [0-9]+ or pass the RegexOptions.ECMAScript parameter to the RegexOptions.ECMAScript constructor)
  • \. - point.

The RegexOptions.Multiline parameter must be passed to the Regex constructor so that ^ matches the beginning of the line. Or add a built-in version of the anchor (?m) at the beginning of the template.

For more information on binding \G see Continuation at the end of the previous match .

See a demo of RegexStorm .

+5
source

Try

 (?<![az].*)\s*\d+\. 

He searches for a sequence of digits \d+ followed by a period \. preceded by any number of space characters \s* . This, in turn, should not precede the letter on the line checked by a negative look-behind (?<![az].*) At the beginning of the regular expression.

Here in RegEx Storm .

0
source

Source: https://habr.com/ru/post/1269509/


All Articles