#๐ Regex help
235 messages ยท Page 1 of 1 (latest)
@steel pollen
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
im new to regex
It looks like your regex will accept 255 fine (unless I missed a typo or something). What it won't accept are two-digit numbers, which is why it won't accept 10 (it would accept 010 though). It also won't accept numbers where the second or third digit are greater than 5 (so no 199 and 246). You can fix all that by spelling out all the possible forms of numbers between 0 and 255, but honestly I think it will be easier to just validate that you have four sequences of 1-3 digits separated by dots and then split on . and convert to int to validate that the numbers are in range.
What if i type 1.2.3.4
ok i got most of that but im not sure how to get those sequences
should i use groups?
then convert to ints
ill try
On another note, it seems weird that your function is called validate, but what it seems to be doing is to search for an IP in the given string.
gets none
I mean stress test that regex. Its gonna be hard ๐
it should return true or false if its a valid ip
But search doesn't return true or false. It returns a match or None. And to return a match, the given string only needs to contain a match. It doesn't have to match the regex in its entirety.
yea i know I can do if statments after to check
oh didnt know the last part
For example, if you input "This text contains the IP 255.255.255.255 haha", then your current code will output "255.255.255.255".
should i use matchfull?
ok sure
now i keep getting none
import re
import sys
def main():
print(validate(input("IPv4 Address: ")))
def validate(ip):
return re.fullmatch(r'[0-2][0-5][0-5]\.[0-2][0-5][0-5]\.[0-2][0-5][0-5]\.[0-2][0-5][0-5]$', ip)
if __name__ == "__main__":
main()
any advice?
As I said, your current regex will not match any numbers with less than three digits (also any number with the digits six through 9 in them).
read this message again :p
oh
yes it does
Right now you're matching for range 0-2 exactly one time
Either change to [0-255] or use [0-2]?[0-5]?[0-5]?
-# Its been a bit since ive used builtin re
[0-255] is rejected in my code
i want to take numbers 0-255
noted, try the other option
[0-255] is another way to write [0125]. That will not do what you want.
Regex101 is your best friend
if you don't mind getting spoiled an answer, check this stack overflow post
latter doesnt work either
Note that [0-2]?[0-5]?[0-5]? will match the empty string (and will still not match 199). I still stand by my earlier suggestion to work with ints instead of regexes to validate the range.
This also wont catch all ips
Split it and do numeric comparison on each int
192.168.0.1 is a valid NAT IP and would fail that regex even if it was working
On an unrelated note, be aware that some tools and APIs interpret leading 0s as indicating octal numbers, so you might not want to allow leading 0s in the IP depending on what you want to do with it.
ah yes ik but for my assignment its fine and i can ignore leading 0s
You should be able to search online for common IP regex algorithms if you're confused
i dont understand half of it tho lol
Use something called Regex 101
Try out regex here and it has an explaination tab on the side. It also comes with a quick reference guide
Thanks!
All you gotta do is make sure you have the python flavour selected otherwise the regex may be slightly different
You code just described
I need 0-2 for first number, 0-5 for second number and 0-5 for the third number
just one last question, how abouts do i check for the first byte? I treid this:
from numb3rs import validate
def test_first():
assert validate("512.512.512.512") == False
for i in "255":
if validate(f"{i}.1.1.1") == False:
assert validate(f"{i}.1.1.1") == False
With dot separation etc.
yea my code doesnt take in all numbers from 0-255
if validate(f"{i}.1.1.1") == False:
assert validate(f"{i}.1.1.1") == False
what?
that will check for each number in "2" "5" "5". (using for on a string iters the chars)
Yeah
i havent done it in a while lol
for i in range(1, 256, 1)
1 - Start point (Inclusive)
256 - End point (EXCLUSIVE!)
1 - Step (not really needed since that's default anyway)
You would need more than 1 options with or in regex
Number of last token to match XD
re.fullmatch(r'^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$', ip)
its this from online
stack overflow
Yeah thats a method :D
lol yea
how to do this?
done this ```py
for i in range(255):
assert validate(f"{i}.1.1.1") == True
Should be for i in range(1, 256, 1) (see my above message for why)
and four of them (nested)
ohh i missed this
thanks
tests arnt testing lol
for i in range(1, 256):
for j in range(1, 256):
for k in range(1, 256):
for l in range(1, 256):
assert validate(f"{i}.{j}.{k}.{l}") == True
im just checking for first byte
you want to vary each byte from 1-255
saves time
Oh god the inefficiency
well the test wants you to check all 4 bytes
test_numb3rs.py catches numb3rs.py only checking if first byte of IPv4 address is in range
expected exit code 1, not 0```
it says first byte here
I assume you're doing this for like learning and stuff
Just checking since the ipaddress module does exist-
im on week 7/9
I'm confused now, I think it wants all 4 bytes to be checked? but yeah the wording isn't really indicative of one way or the other
yea and im not accounting for leading 0s
ill try ur method
yeh it would be
okay anywhere where the rules are clearly laid out?
yea
check this
what does that mean?
The XY problem is You came up with a solution (Y) for problem X, but it wasnt working so you asked how to fix solution Y
byte_data = ip.split()
for byte in byte_data:
if 0<int(byte)<256:
... # Other logic
You check 4 times and its a guaranteed validity.
oh yea
this is smart
*split(".")
yep thanks
probably add a try/except for the non-numerical invalid test cases
!d str.isdecimal or this
str.isdecimal()```
Return `True` if all characters in the string are decimal characters and there is at least one character, `False` otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category โNdโ.
but that might trip you up because it includes 0-9 from other scripts
so try/except it is
Wayyy too used to seeing .isdigit()
Damn
!d str.isdigit
str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
I don't rmb if this one has this quirk or not, but it seems to have other quirks so
yea its good intro
i need to do more projects after i finish tho
Fair fair, if you need inspo, dm me, I always have reasonable ish project ideas
i want to work in finance do u have any inspo?
i dont have access to a terminal like bloomberg tho
i wish i did ๐ฆ
XD Fair
Uhhh finance projects...
Denominations counters
Conversion Calculators
Stock readers (if you cover that sector)
conversion calcs?
ive done a bitcoin indexer using an api
Like GBP to USD or USD to AUD, fetching the latest data ofc
Also ive personally never used pytest, I usually define my own testing methods
its part of cs50
im still failing the tests
Then again im insane apparently as far as devs go XD
Hmm the module does explicitly say about regex...
Im experimenting with the builtin re module instead of the installable one
ok i didnt install anything either
Do you have access to the tests they use for PyTest?
Sigh, if you had access to the tests ๐ญ
ikr
should i just submit
its just one check
im pretty sure i dont need to get all ticks for the cert
Thats how prod apis die
wdym
"Its just one check"
loll
what is it
Im just running a full Ip range test
ok lmk how it is
Could be a while, im remoted onto my dev laptop
ill come back in 10 mins lol
|
?
Ok just dropped python all my threads and 24 worker processes
Still going to take a bit, but nowhere near as long
Golden.
ip_expr = re.compile(
r"\b("
r"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"
r"\."
r"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"
r"\."
r"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"
r"\."
r"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"
r")\b"
)
This is the regex im using
Could allow for an ending .
Besides the fact that windows is screaming for resources right now, its working
shouldnt we just check for the first byte
like it says in the test check
although urs is correct in the long run
it's saying your test only checks for the first byte
Well no because what if its:
"192.269.0.15"
Are you testing... every IP address? Isn't that a little ridiculous?
Oh mines regex testing :D
we make sure it workin
I do think this is the way to go though, but regex works sooo
in my check for 1 byte
i dont want to test for all ips tbh
too long
honestly I'm confused on what the failing test is expecting
P.S you could do this
ip_expr = re.compile(
r"\b("
r"\.".join([r"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"] * 4)
r")\b"
)
Eh true, .join is a thing
removes readability a lil but :P
Also me literally done.
Damn no builtin ipaddress i guess
i need to hardcode values tho
ips = [
"127.0.0.1",
"255.255.255.255",
"512.512.512.512",
"1.2.3.1000",
"192.168.001.1",
"cat"
]
Like that you mean?
For loop through the values and work out what checks you need to pass
I will say, I do have a working implementation
def test_first():
assert validate("256.1.1.1") == False
assert validate("1.256.1.1") == False
assert validate("1.1.256.1") == False
assert validate("1.1.1.256") == False
Hey @steel pollen!
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.