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)
{
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.
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.
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.
The \r metacharacter matches carriage return characters.
simple \r
\n
(carriage return and new line)
/[\r\n]/
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
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With