Regex C# is it possible to use a variable in substitution? -
i got bunch of strings in text, looks this:
h1. header h3. 1 header h111. , and got function, suppose process text depends on lets iteration been called
public void processheadersintext(string inputtext, int atlevel = 1) so output should 1 below in case of been called
processheadersintext(inputtext, 2) output should be:
<h3>this header<h3> <h5>this 1 header too<h5> <h9 , <h9> (last 1 looks because of if value after h letter more 9 suppose 9 in output)
so, started think using regex.
here's example https://regex101.com/r/spb3af/1/
(as can see came regex (^(h([\d]+)\.+?)(.+?)$) , tried use substitution on <h$3>$4</h$3>)
its i'm looking need add logic work heading level.
is possible add work variables in substitution?
or need find other way? (extract heading first, replace em considering function variables , value of header, , after use regex wrote?)
the regex may use is
^h(\d+)\.+\s*(.+) if need make sure match not span across line, may replace \s [^\s\r\n]. see regex demo.
when replacing inside c#, parse group 1 value int , increment value inside match evaluator inside regex.replace method.
here example code you:
using system; using system.linq; using system.text.regularexpressions; using system.io; public class test { // demo: https://regex101.com/r/m9iguo/2 public static readonly regex reg = new regex(@"^h(\d+)\.+\s*(.+)", regexoptions.compiled | regexoptions.multiline); public static void main() { var inputtext = "h1. topic 1\r\nblah blah blah, because of bla bla bla\r\nh2. parta\r\nblah blah blah\r\nh3. part a\r\nblah blah blah\r\nh2. part b\r\nblah blah blah\r\nh1. topic 2\r\nand cuz blah blah\r\nfin"; var res = processheadersintext(inputtext, 2); console.writeline(res); } public static string processheadersintext(string inputtext, int atlevel = 1) { return reg.replace(inputtext, m => string.format("<h{0}>{1}</h{0}>", (int.parse(m.groups[1].value) > 9 ? 9 : int.parse(m.groups[1].value) + atlevel), m.groups[2].value.trim())); } } see c# online demo
note using .trim() on m.groups[2].value . matches \r. may use trimend('\r') rid of char.
Comments
Post a Comment