0

I want to match a string, basically a regex format where in I want to match numbers from 0-255 & 257 above. That means except 256 every number.

Can someone help with the regex format for the same ?

  • 1
    it will depend on which tool you are using as well... regex features vary a lot between tools... also add some sample input and expected output... see regular-expressions.info/numericranges.html for getting started – Sundeep Oct 10 '17 at 4:32
  • 1
    A regex is not the right tool for this task. Care to give some context on the problem? If so, edit the question. Somebody might be able to suggest another method. – NickD Oct 10 '17 at 4:33
  • (1) What have you tried?  (2) What’s the deal with leading zeroes? – Scott Oct 10 '17 at 5:08
  • How about 0x100, 2.56e+2, -256, 0400? Note that in a 256 string there are 5 numbers (2, 5, 6, 25, 56) that are not 256. – Stéphane Chazelas Oct 10 '17 at 7:47
1

As I understand the question, these numbers are all integers. The idea is to match and display entries that contain such numbers but 256, preceeded or not by leading zeros.

Should your numbers be each on a single line:

grep "^[0-9][0-9]*$" | grep -v "^0*256$"

(grep -v excludes lines that match instead of including them)

Ouput:

$ echo "12" | grep "^[0-9][0-9]*$" | grep -v "^0*256$"
12

$ echo "2567" | grep "^[0-9][0-9]*$" | grep -v "^0*256$"
2567

$ echo "256" | grep "^[0-9][0-9]*$" | grep -v "^0*256$"

$ echo "0256" | grep "^[0-9][0-9]*$" | grep -v "^0*256$"

$ echo "something" | grep "^[0-9][0-9]*$" | grep -v "^0*256$"

Should you be using another separator:

You can for example preprocess your inputs using sed to make them compatible with the grep commands above. Here with a coma-delimitated input where each coma is replaced by a line-feed (\n):

sed -r 's/,/\n/g'

Output:

$ echo "2567,255,256,12,something,05,0256" | sed -r 's/,/\n/g' | grep "^[0-9][0-9]*$" | grep -v "^0*256$"
2567
255
12
05

And finally, should your numbers be mixed with other random characters:

In that case, an extra step allows removing all non-numerical characters:

sed -r 's/[^0-9]//g'

Output:

$ echo "2567,255,256,mama256a,papa1812b,something,05,0256" | sed -r 's/,/\n/g' | sed -r 's/[^0-9]//g' | grep "^[0-9][0-9]*$" | grep -v "^0*256$"
2567
255
1812
05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.