我有基本模式:
Input = Regex.Replace(Input, "#(.+?)#", "<h3>$1</h3>");
现在我只希望这匹配IF它所在的行不以4个空格字符开头。例如:
This line #would match#
#this one# wouldn't
我到目前为止:
Input = Regex.Replace(Input, "^( {4}).?#(.+?)#", "<h3>$2</h3>");
但这似乎不起作用;它没有正确替换。这是一些测试数据:
#This is my header#
Some text, code below:
background:#333333;
background: #ffffff, #000000;
Testing text
#Another header#
Text
答案 0 :(得分:2)
您可以使用负向lookbehind声明输入中没有出现四个空格,如下所示:
"(?<!^ )#(.+?)#"
但是在应用正则表达式之前检查它可能更具可读性。
if (!Input.StartsWith(" "))
Input = Regex.Replace(Input, "#(.+?)#", "<h3>$1</h3>");
答案 1 :(得分:1)
为什么不直接检查是否存在4个空格?
if(line.StartsWith(" "))
{
var text = line.Substring(4, line.Length - 4);
text = "<h3>" + text + "</h3>";
}
答案 2 :(得分:1)
Input = Regex.Replace(Input, "^(?! {4})(.*?)#(.+?)#", "$1<h3>$2</h3>");
首先,断言该行不以四个空格开头:^(?! {4})
。
然后捕捉做开头的任何内容,如果它不是您实际匹配的内容:(.*?)
。
最后,在进行真正的替换之前,先将初始字符(可能只是一个空字符串)插入:$1<h3>$2</h3>
。
答案 3 :(得分:0)
您当前的正则表达式搜索做以四个空格开头的行 - 这就是为什么它不起作用。
您可以使用否定前瞻来解决您的问题:
Input = Regex.Replace(Input, "^(?! {4})(.*)#(.+?)#", "$1<h3>$2</h3>");
这匹配从头开始的行(^
)
(?! {4})
,#...#
(.*)
之前的余数
#(.+?)#
中捕获。答案 4 :(得分:0)
Input = Regex.Replace(Input, "(?<!\\s{4})#(.+?)#", "<h3>$1</h3>");