Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to not match new line

Tags:

regex

emacs

The below regex should match only the lines that does not start with # character followed by anything.

^[^#].*

But if the buffer contains a empty line before it it matches the next line even if it starts with #.

For the following input it fails

This line is matched as expected

# this line should not be matched, but it does if the above line is empty !?
like image 896
Talespin_Kit Avatar asked Nov 14 '13 14:11

Talespin_Kit


People also ask

Does regex include newline?

By default in most regex engines, . doesn't match newline characters, so the matching stops at the end of each logical line. If you want . to match really everything, including newlines, you need to enable “dot-matches-all” mode in your regex engine of choice (for example, add re. DOTALL flag in Python, or /s in PCRE.

What is \r and \n in regex?

Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

How do you match line breaks in regex?

If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”. Whether or not you will have line breaks in your expression depends on what you are trying to match. Line breaks can be useful “anchors” that define where some pattern occurs in relation to the beginning or end of a line.

Does \s match new line?

According to regex101.com \s : Matches any space, tab or newline character.


1 Answers

You can fix it like this:

^[^#\r\n].*

The problem with your original expression ^[^#].* is that [^#] was matching the newline character (the empty line), thus allowing the dot . to match the entire line after the empty one, so the dot isn't actually matching the newline, the [^#] is the one doing it.

Regex101 Demo

like image 129
Ibrahim Najjar Avatar answered Oct 12 '22 12:10

Ibrahim Najjar