Tom Gullen
Tom Gullen

Reputation: 61735

C# Regex for string that doesn't start with 4 chars

I have the basic pattern:

Input = Regex.Replace(Input, "#(.+?)#", "<h3>$1</h3>");

Now I only want this to match IF the line it's on DOESN'T start with 4 space characters. For example:

This line #would match#
    #this one# wouldn't

I've got as far as:

Input = Regex.Replace(Input, "^( {4}).?#(.+?)#", "<h3>$2</h3>");

But this doesn't seem to work; it doesn't replace properly. Here's some test data:

#This is my header#

Some text, code below:

    background:#333333;
    background: #ffffff, #000000;

Testing text

#Another header#

Text

Upvotes: 2

Views: 833

Answers (5)

Jason
Jason

Reputation: 3960

Input = Regex.Replace(Input, "(?<!\\s{4})#(.+?)#", "<h3>$1</h3>");

Upvotes: 0

Alan Moore
Alan Moore

Reputation: 75242

Input = Regex.Replace(Input, "^(?! {4})(.*?)#(.+?)#", "$1<h3>$2</h3>");

First, assert that the line doesn't start with four spaces: ^(?! {4}).

Then capture whatever it does start with, if it's not the stuff you're actually matching: (.*?).

And finally, plug the initial characters (which could be simply an empty string) back in before you do the real replacement: $1<h3>$2</h3>.

Upvotes: 1

Heinzi
Heinzi

Reputation: 172310

Your current regex searches for lines which do start with four spaces -- that's why it doesn't work.

You can solve your problem with a negative lookahead:

Input = Regex.Replace(Input, "^(?! {4})(.*)#(.+?)#", "$1<h3>$2</h3>");

This matches lines that, from the beginning (^),

  • do not start with four spaces (?! {4}),
  • the remainder until #...# is captured in group 1 (.*)
  • #...# is captured in group 2 #(.+?)#.

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 191965

You can use a negative lookbehind to assert that four spaces have not appeared in the input, like so:

"(?<!^    )#(.+?)#"

But it would probably more readable to just check before applying the regex.

if (!Input.StartsWith("    "))
    Input = Regex.Replace(Input, "#(.+?)#", "<h3>$1</h3>");

Upvotes: 2

Tejs
Tejs

Reputation: 41246

Why not simply check for the existance of 4 spaces?

 if(line.StartsWith("    "))
 {
     var text = line.Substring(4, line.Length - 4);
     text = "<h3>" + text + "</h3>";
 }

Upvotes: 1

Related Questions