r/learnpython • • Dec 04 '20

Just wrote my first real Regex's for Advent of Code Day 4

I can identify whether a string is 9 numbers in a row. I am a god and can bend computers to my will.
For real though, it feels amazing to have written something that looks like gibberish but actually works, even if it's actually pretty simple. Now I don't have to mess around with 30 nestled if statements and .split() statements. Regex's are pure magic.

335 Upvotes

35 comments sorted by

80

u/xelf Elf Dec 04 '20

Congrats! ๐Ÿ†

Did you see the people that solved the thing with 1 gigantic regex? Absolute nuts.

Seriously look at this mess:

(((byr:(19[2-9]\d|200[0-2]))|(iyr:(201\d|2020))|(eyr:(202\d|2030))|(hgt:(((59|6\d|7[0-6])in)|(1([5-8]\d|9[0-3])cm)))|(hcl:#[0-9a-f]{6})|(ecl:(amb|blu|brn|gry|grn|hzl|oth))|(pid:(\d{9}))|(cid:([^ \n]*)))( |\n|$)){8}|(((byr:(19[2-9]\d|200[0-2]))|(iyr:(201\d|2020))|(eyr:(202\d|2030))|(hgt:(((59|6\d|7[0-6])in)|(1([5-8]\d|9[0-3])cm)))|(hcl:#[0-9a-f]{6})|(ecl:(amb|blu|brn|gry|grn|hzl|oth))|(pid:(\d{9})))( |\n|$)){7}

*left as not code block so it will wrap

credit

19

u/shinitakunai Dec 05 '20

That one is small. I use one at work that needs to take into account all possible dates to validate user input, with / delimiters and leap years... i am in a hate/love relationship with that one, 90% hate

→ More replies (1)

6

u/[deleted] Dec 04 '20

Woww didnโ€™t know this was possible, like op I wrote my first regex as well but only for the hcl (Hair Color) part

6

u/xelf Elf Dec 04 '20

I suspect that there will be a call back to this puzzle, so you might be in a better place having not written it as one throw away regex. =)

5

u/[deleted] Dec 04 '20

You might be interested in this: https://www.youtube.com/watch?v=Q2g9d29UIzk

8

u/zombiepirate2020 Dec 05 '20

I have questions and concerns at this point.

My concern is that I am completely insane.

My question is, are all of you insane as well?

2

u/Katatoniczka Dec 05 '20

Oh... I was proud of my 10000 ifs... :(

→ More replies (1)

35

u/YmFzZTY0dXNlcm5hbWU_ Dec 04 '20

Mastering regex is a great feeling. Highly recommend you check out the engineer man video on YouTube about that if you want more info on the basics. regex101.com is also a great resource to test expressions (and the quiz/game mode taught me a lot as well, especially trying to optimize my correct but lame answers).

11

u/ASIC_SP learnbyexample Dec 05 '20

In addition to regex101, I'll recommend these:

Also, I have a free web book covering both re and third-party regex module with hundreds of examples and exercises: https://learnbyexample.github.io/py_regular_expressions/

→ More replies (1)

8

u/SultanofShiraz Dec 04 '20

Wait... I use this site all the time.. and OMG, THERE'S QUIZZES AND GAMES!!! RIP rest of the day.

4

u/YmFzZTY0dXNlcm5hbWU_ Dec 05 '20

Just wait until you find out what a regex crossword is. RIP the rest of your weekend

2

u/poogzilla Dec 05 '20

Thanks for the tip on the Engineer Man video! RegEx is something that I get overwhelmed by and that really made it more palatable.

→ More replies (1)

2

u/sentry07 sentry07 Dec 05 '20

Love regex101. Itโ€™s my go-to validator. Was not aware of any games on there. Must go play!

14

u/primitive_screwhead Dec 05 '20

Now I don't have to mess around with 30 nestled if statements

Consider the power of set operations, also:

given_input = '078332912'
if len(given_input) == 9 and set(given_input).issubset('0123456789'):
    return True

(or, if you need other definitions from the string module anyway):

import string

given_input = '078332912'
if len(given_input) == 9 and set(given_input).issubset(string.digits):
    return True

7

u/[deleted] Dec 05 '20

REGEX IZ CHEETIN
Change my mind. joking

3

u/mikeblas Dec 05 '20

Someone who solves a problem with a regular expression now has two problems.

4

u/kabooozie Dec 05 '20

Regexr.com is the best

1

u/fmpundit Dec 05 '20

What did your pattern look like? I had \d{9} but it was picking up PID that had 9+ digits in a row. I had to run a if Len() over it.

2

u/enderflop Dec 05 '20

I used
[0-9]{9}$
but I think that
\b\d{9}\b
might work even better in case 9 numbers may be in the middle of a sentence

2

u/pipeaday Dec 05 '20

Similar experience here - used regex basically for the first time ever for part 2, in conjunction with Cerberus for the data validation. Super cool to see something work in a not-completely-trivial example

2

u/Wonder1and Dec 05 '20

I use this a ton for work but in notepad++ for log file hunting and manipulation. Totally worth checking out for practicing regex straight. Just open the ctrl+f / search window, click the replace tab and use radio button for "Regular Expression" at the bottom left.

Example syslog message line:

<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - IDW47 [exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"] BOMAn application event log entry for all the bases

Find:

.{7}\d{4}\-\w{2}\-\w{2}(\w)[0-9:.]+Z(\s)\w(\w)\w(\w)\w(\w)(\w)\w{2}\.\w+\.\w{3}\s(\w)\w{3}(\w)?.+\-\s[A-Z]{2}(\w).+

Replace:

\1\5\6\8\2\6\8\2\1\5\7\2\9\4\3

2

u/supersede Seasoned Intermediate Dec 05 '20

good, now don't overuse it. i work with some people who have regex boners and use them incessantly when they really aren't needed and you can use a single split or partition to get a value you want, which is way more readable and arguably more pythonic.

3

u/zanfar Dec 05 '20

24 comments and no one has linked the XKCD?!?!

https://imgs.xkcd.com/comics/regular_expressions.png

1

u/javaHoosier Dec 05 '20

If you learn the syntax for how automata are written in regular expressions it helps intuitively understand it a lot better. Although modern regex is more complex. I had some a-ha moments.

1

u/gngg2011 Dec 05 '20

RIP me, got stuck on the second half with a logical error :(

1

u/set22 Dec 05 '20

Read a little about finite state machines/ regular languages. Just learn that in my discrete class and itโ€™s very cool. Helped me get comfortable with regex. I also used it yesterday on AOC for the first time comfortably

1

u/blight000 Dec 05 '20

Congrats! I started trying to write regex but then gave up and used loops and conditional statements instead...

0

u/[deleted] Dec 05 '20

[deleted]

2

u/enderflop Dec 05 '20

I've been working through the 2015 puzzles and I had to translate a guys JavaScript code to python to solve day 7. went to the comments on the days thread and the host was in there saying "if you think day 7 is bad just wait!" I've solved day 8 but I'm in the same boat as you, just waiting to hit that wall

2

u/[deleted] Dec 04 '20

[removed] โ€” view removed comment

4

u/enderflop Dec 04 '20

edit: was thinking of eye color. yeah, I used an even more complex REGEX for it and actually figured it out first. lots of googling and experimenting in a test python file involved