Regex to check for new line

2020-08-26 11:01发布

问题:

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)
{

回答1:

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

/[\r\n]/


回答2:

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


回答3:

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.



回答4:

As you want to check this specifically for an if, use this:

(if[ ()\w=]+)\r\n

returns true if the if has a newline and false if not.



回答5:

You are looking for if statements that don't use curly braces, but your pattern requires curly braces.

Here is my suggestion: (Demo)

$strings = [
'if (blah === blah)
    do something',
'if (foo === foo) do something',
'if (bah === bah) {
    do something
}',
'if (bar === bar) {do something}'
];

foreach ($strings as $string) {
    var_export(preg_match('~if\s*\(.*?\)\s*(\{)?~', $string, $m) ? $m : '');
    echo "\nHas curly brace: " , isset($m[1]) ? 'Yes' : 'No';
    echo "\n---\n";
}

Output:

array (
  0 => 'if (blah === blah)
    ',
)
Has curly brace: No
---
array (
  0 => 'if (foo === foo) ',
)
Has curly brace: No
---
array (
  0 => 'if (bah === bah) {',
  1 => '{',
)
Has curly brace: Yes
---
array (
  0 => 'if (bar === bar) {',
  1 => '{',
)
Has curly brace: Yes
---

Basically, use \s* to signify where no space/newlines, a space/newline, multiple spaces/newlines may occur in the markup.

My pattern will not catch if statements with multi-line expressions. To accommodate those fringe cases, add the s pattern modifier to allow the . to match newlines.



标签: php regex