Lucy
Lucy

Reputation: 13

Regex match pattern

I am trying to count the amount of times I use \n\n\n (3 linebreaks) after some text. It counts almost as I like, the problem is when you spam newlines that will be counted which I don't want to.

Edit: Seems like the regex from regexr does not support .net so I have to come up with a pattern that works with .net.

Example for the text that the regex will check on:

Description for something

text \n \n \n // this will make DescriptionAmount++

Description for something

text\n \n \n // this will make DescriptionAmount++

\n \n \n // this shouldn't add on DescriptionAmount

Here's the code I've done so far.

int DescriptionAmount = Regex.Matches(somestring, "[^\w$](\r\n){2}[^\w$]").Count;

Upvotes: 0

Views: 72

Answers (2)

Brandon Griffin
Brandon Griffin

Reputation: 348

To ensure you capture the 3 linebreaks after some text would take something like:

\w+\s*\n{3}

Since this is .net, you either need to put an @ in front:

@"\w+\s*\n{3}

or escape the slashes like:

"\\w+\\s\n{3}

You mentioned that you are searching for three \n, but your search has \r\n. If you are looking for \r\n instead, just add \r in front of the \n and surround with () for (\\r\\n) or (\r\n) in the expressions above.

One other thing, depending on the text in some string, you may want to apply the multiline option like:

Regex.Matches(somestring, "\\w\\s\n{3}", RegexOptions.Multiline)

Upvotes: 0

donners45
donners45

Reputation: 361

Try using a quantifier {x,y} to select how many tokens you want to match.

The '*' will match the preceding character 0 or many times, meaning it will match any \n after the 3rd token.

\n{3} says \n must be matched 3 times no more no less.

I find this tool http://regexr.com/ very useful for building and debugging regex statements.

Upvotes: 1

Related Questions