Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check for new line

Tags:

regex

php

I want to check if an if statement is on one line or the next line without a brace like so:

if (blah === blah)
    do something

or:

if (foo === foo) do something

The regex i have currently is

/\)(?!.*\{)/

But doesnt work. Anyone have any ideas?

To elaborate the only If statement that would not be pulled by this regex is the following:

if (foo === bar)
{
like image 282
Cjmarkham Avatar asked Aug 24 '12 14:08

Cjmarkham


People also ask

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 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.

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.

What does \r do in regex?

The \r metacharacter matches carriage return characters.


3 Answers

simple \r \n (carriage return and new line)

/[\r\n]/
like image 124
Mihai Iorga Avatar answered Sep 21 '22 08:09

Mihai Iorga


New lines may be \n (UNIX), \r\n (Windows), \r (for good measure). The expression to broadly match new lines is:

/\r\n|\r|\n/

To check if an expression is on one line, you can do this:

if( preg_match( '/\r\n|\r|\n/', $string ) ) {
    // on more than one line
    ...
} else {
   // on one line
   ...
}

To further develop this to apply to your specific example of an if ... do statement, you could do this:

if( preg_match( '/if *\([^\)]+\) *(\r\n|\r|\n) *do /', $string ) ) {
    // on more than one line
    ...
} elseif( preg_match( '/if *\([^\)]+\) *do /', $string ) ) {
   // on one line
   ...
}
like image 26
kingjeffrey Avatar answered Sep 22 '22 08:09

kingjeffrey


You need to make . match newlines, too:

/\)(?!.*\{)/s
            ^
    PCRE_DOTALL Modifier

This is done with the s (PCRE_DOTALL ) modifier (as written in comments):

s (PCRE_DOTALL)

If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

like image 32
hakre Avatar answered Sep 21 '22 08:09

hakre