1

I have these lines:

MyString                 33
MyString                 10
MyString                 3
MyString                 5

I want to get match on all the lines that doesn't have the specific number: 3.
Therefore, I need to get match on these numbers:

MyString                 33
MyString                 10
MyString                 5

But not on:

MyString                 3

This is what I tried:

MyString                 ^(?!3)
MyString                 ^(3)
MyString                 (^?!3)
MyString                 (^3)

But none of them worked.
I don't have much experience with regex.
I used this website for as a guide:
https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

I also read similar questions:
Exclude certain numbers from range of numbers using Regular expression Exclude a set of specific numbers in a "\d+" regular expression pattern

But I still didn't understand how to do it.

E235
  • 11,560
  • 24
  • 91
  • 141

3 Answers3

2

you can use the regex

MyString                 (?!3\b)\d+

see the regex demo

Negative Lookahead (?!3\b)
Assert that the Regex below does not match the character 3 literally
\b assert position at a word boundary

marvel308
  • 10,288
  • 1
  • 21
  • 32
  • 1
    I think `\b` or `$` are better than of `\n`. What do you think? – linden2015 Aug 20 '17 at 14:22
  • I ran it on large file, and the "\n" did some problems (receiving match on lines with "3") but after you edit it with "\b" it seems to work good. Thanks. – E235 Aug 20 '17 at 14:26
2

A working solution:

\w+\s+(?!3\b)\d+

\w+      # 1 or more word characters
\s+      # 1 or more white-space characters
(?!3\b)  # looking ahead, this group may not match (\b is a word boundary)
\d+      # 1 or more digits

Demo

linden2015
  • 887
  • 7
  • 9
1

You could use the expression:

grep -v '^3$' yourFile

In this way, you are asking to find:

  1. All strings starting (^) with 3
  2. All strings terminating ($) with 3
  3. All strings that have only one 3 in them

From this, you have selected all the strings containing only the number 3. Reverse selection with the flag -v to get what you want.

Hope it helps.

Neb
  • 2,270
  • 1
  • 12
  • 22