rahlzel
rahlzel

Reputation: 41

Regex: Line does NOT contain a number

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

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?

Upvotes: 0

Views: 2583

Answers (5)

stema
stema

Reputation: 92986

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

Upvotes: 2

Bart Kiers
Bart Kiers

Reputation: 170158

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

Upvotes: 0

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

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

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

print_r($lines);

?>

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

Would grep -v 377681 input_file solve your problem?

Upvotes: 2

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

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?

Upvotes: 0

Related Questions