0

So I have been trying to build a regex that would detect port numbers(0-65535). I have tried the one given in the post below:

Regex to validate port number

this one :

^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$

The above one seems to work fine when testing on https://regex101.com/.

But when I try to build a yara rule to detect this with the same pattern as stated above it doesn't work even though the above pattern has all the allowed characters as stated in the documentation:

https://yara.readthedocs.io/en/stable/writingrules.html#regular-expressions

Toto
  • 89,455
  • 62
  • 89
  • 125

2 Answers2

0

Your regex has starting (^) and end point ($) check. Because of this it will work only if your input is a port number. This will not work if you want to match the port number part from a string. To work this for a string remove ^ and $ from the regex start and end point.

jnrdn0011
  • 417
  • 2
  • 13
  • When I put these characters at the start and beginning, It does not detect any port number I give it (for example 4444) . Do note that I am using this in yara rule. And when I remove the characters from start and beginning, it just sees every number i input as a port number. my regex:/([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])/ – Khizar Ul Haq Jun 09 '20 at 08:29
  • Replace `^` and `$` by `\b` then. `\b` is a word boundary; The boundary between word-characters (`[A-Za-z0-9_]`) and non-word characters (anything else). The pattern would match a number between 0 and 65535 without any surrounding digit or letter. – Markus Jarderot Jun 10 '20 at 07:49
  • Is this what you are suggesting? /\b([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\b/ – Khizar Ul Haq Jun 10 '20 at 08:01
  • @MarkusJarderot can you kindly post this as an answer so I can accept it. Thanks again – Khizar Ul Haq Jun 10 '20 at 08:38
0

Replace ^ and $ by \b.

\b([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])\b

\b is a word boundary; The boundary between word-characters ([A-Za-z0-9_]) and non-word characters (anything else). The pattern would match a number between 0 and 65535 without any surrounding digit or letter.

Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138