开发者

Regex: Line does NOT contain a number

开发者 https://www.devze.com 2023-03-24 02:38 出处:网络
I\'ve been racking my brain for hours on this and I\'m at my wit\'s end. I\'m beginning to think that this isn\'t possible for a regular exp开发者_运维技巧ression.

I've been racking my brain for hours on this and I'm at my wit's end. I'm beginning to think that this isn't possible for a regular exp开发者_运维技巧ression.

The closest thing I've seen is this post: Regular expression to match a line that doesn't contain a word?, but the solution doesn't work when I replace "hede" with the number.

I want to select EACH line that DOES NOT contain: 377681 so that I can delete it.

^((?!377681).)*$ 

...doesn't work, along with thousands of other examples/tweaks that I've found or done.

Is this possible?


Would grep -v 377681 input_file solve your problem?


Try this one

^(?!.*377681).+$

See it here on Regexr

Important here is to use the m (multiline) modifier, so that ^ match the start of the line and $ the end of the row, other wise it will not work.

(Note: I recognized that my regex has the same meaning than yours.)


There's probably a better way of doing this, like for example iterating each line and asking for a built String method, like indexOf or contains depending on the language you're using.

Could you give us the full example?


<?php
$lines = array(
'434343343776815456565464',
'434343343774815456565464',
'434343343776815456565464'
);

foreach($lines as $key => $value){
    if(!preg_match('#(377681)#is', $value)){
        unset($lines[$key]);
    }   
}

print_r($lines);

?>


You'll need to enable the m (multi-line) flag for the ^ and $ to match the start- and end-of-lines respectively. If you don't, ^ will match the start-of-input and $ will only match the end-of-input.

The following demo:

#!/usr/bin/env php
<?php
$text = 'foo 377681 bar
this can be 3768 removed
377681 more text
remove me';

echo preg_replace('/^((?!377681).)*$/m', '---------', $text);
?>

will print:

foo 377681 bar
---------
377681 more text
---------
0

精彩评论

暂无评论...
验证码 换一张
取 消