r/badcode • • Sep 21 '20

python Yes. Why use RegEx.

Post image
747 Upvotes

127 comments sorted by

164

u/gnutrino Sep 21 '20

I know people with an irrational fear of regex who will go to great lengths to avoid using it.

154

u/[deleted] Sep 21 '20

Maybe they looked at the General Email Regex (RFC 5322 Official Standard) and got scared:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

87

u/Razakel Sep 21 '20

The best part is that's not even complete. It fails to validate legal, if unusual, email addresses.

This is the complete one:

(?:(?:\r\n)?[ \t])(?:(?:(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?: \r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:( ?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t])))@(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\0 31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([[]\r\]|\.)*
](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+ (?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([[]\r\]|\.)*](?: (?:\r\n)?[ \t])))|(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n) ?[ \t]))<(?:(?:\r\n)?[ \t])(?:@(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:
r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n) ?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t] )))(?:,@(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([^[]\r\]|\.)](?:(?:\r\n)?[ \t])* )(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[["()<>@,;:\".[]]))|[([^[]\r\]|\.)](?:(?:\r\n)?[ \t])))) :(?:(?:\r\n)?[ \t]))?(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+ |\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r \n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?: \r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t ]))"(?:(?:\r\n)?[ \t])))@(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031 ]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([^[]\r\]|\.)]( ?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(? :(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([[]\r\]|\.)*](?:(? :\r\n)?[ \t])))>(?:(?:\r\n)?[ \t]))|(?:[<>@,;:\".[] \000-\031]+(?:(? :(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)? [ \t]))"(?:(?:\r\n)?[ \t])):(?:(?:\r\n)?[ \t])(?:(?:(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]| \.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<> @,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|" (?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t])))@(?:(?:\r\n)?[ \t] )(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\ ".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(? :[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[ ]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t])))|(?:[<>@,;:\".[] \000- \031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\.|( ?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t]))<(?:(?:\r\n)?[ \t])(?:@(?:[<>@,; :\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([ []\r\]|\.)*](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\" .[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([[
]\r\]|\.)*](?:(?:\r\n)?[ \t])))(?:,@(?:(?:\r\n)?[ \t])(?:[<>@,;:\".
[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([^[]
r\]|\.)](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|[([[]\r\] |\.)](?:(?:\r\n)?[ \t])))):(?:(?:\r\n)?[ \t]))?(?:[<>@,;:\".[] \0 00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|"(?:["\r\]|\ .|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[<>@, ;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[]]))|"(? :["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t])))@(?:(?:\r\n)?[ \t]) (?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\". []]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t])(?:[ <>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[] ]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t])))>(?:(?:\r\n)?[ \t]))(?:,\s( ?:(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\ ".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t]))(?:.(?:( ?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[ ["()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t ])))@(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t ])+|\Z|(?=[["()<>@,;:\".[]]))|[([^[]\r\]|\.)](?:(?:\r\n)?[ \t]))(? :.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+| \Z|(?=[["()<>@,;:\".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t])))|(?: [<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\".[
]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t]))<(?:(?:\r\n) ?[ \t])(?:@(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[[" ()<>@,;:\".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n) ?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<> @,;:\".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t])))(?:,@(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@, ;:\".[]]))|[([^[]\r\]|\.)](?:(?:\r\n)?[ \t]))(?:.(?:(?:\r\n)?[ \t] )(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\ ".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t])))):(?:(?:\r\n)?[ \t]))? (?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[["()<>@,;:\". []]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t]))(?:.(?:(?: \r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[[ "()<>@,;:\".[]]))|"(?:["\r\]|\.|(?:(?:\r\n)?[ \t]))"(?:(?:\r\n)?[ \t]) ))@(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t]) +|\Z|(?=[["()<>@,;:\".[]]))|[([^[]\r\]|\.)](?:(?:\r\n)?[ \t]))(?:
.(?:(?:\r\n)?[ \t])(?:[<>@,;:\".[] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[["()<>@,;:\".[]]))|[([[]\r\]|\.)*](?:(?:\r\n)?[ \t])))>(?:( ?:\r\n)?[ \t]))))?;\s*)

56

u/AnusDickPenetrator69 Sep 21 '20 edited Sep 21 '20

Not even that is the complete one... it gets worse:

https://pastebin.com/cDDcgrWb

(22k characters, too long for reddit comments)

28

u/Razakel Sep 21 '20

You're right, just skimming the one I posted I don't think it handles Unicode. 😁@🙂. is technically a valid email address.

23

u/fernandotakai Sep 21 '20

that's why you should:

  1. check if the email has an @

  2. send a verification email to that email

it's the easiest email validation ever.

20

u/cpaca0 Sep 21 '20

Has anyone grabbed that yet?

Can I steal 😁@🙂

16

u/Razakel Sep 21 '20

If you can afford the ICANN fee to apply for a new TLD.

4

u/Catlover790 Sep 21 '20

what is the price

8

u/Razakel Sep 21 '20

$185,000.

5

u/jarfil Sep 22 '20 edited Dec 02 '23

CENSORED

→ More replies (0)

2

u/[deleted] Sep 22 '20

You don't need a TLD. Emoji subdomains are valid: https://en.m.wikipedia.org/wiki/Emoji_domain

2

u/Razakel Sep 22 '20

So are email addresses where the hostname is just a TLD. There's a web page at http://ai./ and it has MX records.

7

u/AnusDickPenetrator69 Sep 21 '20

!@! is technically a valid one too, lol

6

u/ColdPorridge Sep 22 '20

Why am I positive even if you somehow got this working my shitty bank’s input validation would tell me it’s not a valid email.

4

u/Mango1666 Sep 21 '20

what the fuck

7

u/uhredditaccount Sep 22 '20

Unicode the fuck

39

u/efko0ss Sep 21 '20

That's exactly how my fear of regex started.

18

u/Not_Sugden Sep 21 '20

!!!!!!!!!!!!!!!!!!!

18

u/brylee123 Sep 21 '20

You mean I can't just use:

.+@.+\..+

time to roll back some code I wrote for some nuclear missiles

6

u/R3D3-1 Sep 21 '20

I think pretty much any string containing exactly one @ is a valid email address.

7

u/christian-mann Sep 21 '20

"thi$ is a v@lid [email protected] @ddr*ss+"@example.com

2

u/Fried_Squid_ Sep 21 '20

​@​

(U+200B@U+200B)

0

u/[deleted] Sep 21 '20

[deleted]

5

u/fernandotakai Sep 21 '20

honestly, it's the only valid way, specially with all the weird tlds that are being launched.

5

u/omegasome Sep 22 '20 edited Feb 03 '21

@@@.@ matches that, and that better fuckin not be a valid email address or I'm gonna have to resurrect Harald Bluetooth to go on a crusade with me

1

u/[deleted] Feb 02 '21

That’s a valid email. Technically I think @@@ is valid

1

u/omegasome Feb 03 '21

Resurrection it is then.

Choono slalem denni tay'lori olee-ay.

1

u/[deleted] Feb 03 '21

if you slap a @ in there, that could also be a valid email

1

u/omegasome Feb 03 '21

You're first, Sar@cen

1

u/[deleted] Feb 03 '21

emails are weird.

5

u/itsTyrion Sep 21 '20

!? wat

3

u/trevhcs Sep 21 '20

They said: "?((*" err, well wot he / she sed. ;)

2

u/Optimal_FruitCake Sep 21 '20

For me it was the UK postcode validation.

([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})

And the weird ass phone numbers

^(?:(?:\(?(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?(?:\(?0\)?[\s-]?)?)|(?:\(?0))(?:(?:\d{5}\)?[\s-]?\d{4,5})|(?:\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3}))|(?:\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4})|(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}))(?:[\s-]?(?:x|ext\.?|\#)\d{3,4})?$

1

u/bschlueter Sep 22 '20

The number of sites that don't accept my one character @ my domain . blue is too damn high.

34

u/dam4rus Sep 21 '20

I've had such co-worker. When I refactored his 60 line monstrosity into a relatively simple regexp he replied with: "but... performance?!". Then he wasted 1-2 hours to measure how much slower the regexp version is.

16

u/Nall-ohki Sep 21 '20

Send him a bill for his time.

9

u/GoldenKela Sep 21 '20

so is regex slower, in practice?

19

u/dam4rus Sep 21 '20

Short answer: Yes but you shouldn't care about it if it makes the code more readable and your application or the part of the code is not performance critical.

Long answer: Yes but the slowdown greatly depends on the implementation. This was C++ mind you and pcre2 was about 2-3x slower. Meanwhile Visual Studio's implementation at the time were about 16x (!) slower. IIRC Python's implementation is just as slow. The actual compilation of the regex isn't included in these metrics btw. Compilation can actually take a lot of time so ALWAYS compile and reuse your regex if you can.

2

u/sharkbound Sep 23 '20

IIRC python automatically compiles and caches RegEx for you

1

u/dam4rus Sep 23 '20 edited Sep 29 '20

Not really. If you pass a string to any "re" module function it will compile it to regex code but doesn't cache it. So it's better to use "re.compile" and pass the code object if you intend to use it multiple times.

Edit: I know it's an old reply but I just read the documentation and you are right. It caches the most recent RegEx-s. It doesn't state how many so I still think it's better to compile it before using.

5

u/trevhcs Sep 21 '20

Very since you normally have to run the reg ex translator against it and those are even more complicated. As in nose bleed inducing complex.

In this case its doing that on each bit and that will send your computer into meltdown.

3

u/cajuncoding Sep 25 '20 edited Sep 25 '20

Bikeshedding! I deal with another tech person at my client that does the same thing all the time... spending days/weeks perfomrnce testing things like whether a list is faster than a hashset in a iterative repetitive lookup.... but 2 methods up and one over there was code running with an N+1 issue for Database lookups that would blow your mind (taking 30+ seconds)...

I'm like NO a List is not faster... and NO it's not worth my time to prove it... look over here at the statistically significant issue!

And yes your Regex could very well be faster... if it doesn't do any unnecessary backtracking and/or your input text size is reasonable!

2

u/dam4rus Sep 25 '20

To be fair, as a C++ developer I tended to do the same. Assuming something is slower because it looks more complex than using basic control flow statements. A lot of the time I was proven wrong and over time I stopped caring about it. Sometimes my "better tuned" code actually hurt performance. Readability and maintainability is way more important. If something is visibly slow, sure, try to improve performance. But, as you said, when you have to wait multiple seconds for API calls, database accesses, etc. gaining a few milliseconds at best is basically worthless.

2

u/cajuncoding Sep 25 '20 edited Sep 26 '20

Totally agree.

Specifically regarding regex I see developers trying to do too much with a single regex expression (nearly always not being pre-compiled; simple optimization that nets you 80/20 benefit).

When in reality the code would be much less complex with more than one expression (within reason) whereby each focuses on a specific task and is more readable! Thereby making maintenance and understanding much better!

Oh and use named captures whenever available...it makes a huge difference in readability!

Plus with the great online debuggers for regex I find that they result in far fewer edge case bugs than the manual string manipulation code that is replaced by them !

Finally if performance really truly is that important then look into result or token caching and get the best of it all.

1

u/GavinZac Sep 22 '20

So: it worked, it was faster, and more readable; so you made it slower, less readable, and untested, to... save bytes? Scrollbar pixels? And you accuse him of wasting time. Congrats.

2

u/dam4rus Sep 22 '20

I don't know if you are serious or not. Yes, it worked. So did my solution which I tested. If you think a 60 line monstrosity to extract some substrings is more readable than a regex I question your sanity. As I've said, it was a very simple regex matching key=value pairs separated by a separator, capturing the values. And yes it was slower but the code ran like 2 times at the start of the application on a small string. So I've slowed it down from running in 0 ms to 0 ms. Once per run. And I did it so it. will. be. readable. His implementation was also incorrect.

2

u/cajuncoding Sep 25 '20

Yep, sounds like u/dam4rus did a perfect example of valid refactoring for maintenance... in many many cases a regex can yield much more readable code than manual string manipulation.... especially if you put the extra effort to use named captures (in implementations that support it).

And if the other developer is reasonable they should learn something from the exercise in refactoring too... so there's a lot of value to be had even if the initial implementation wasn't flawed, which apparently it was.

1

u/GavinZac Sep 25 '20

Learn and fix it next time.

Don't. Touch. Working. Code. I swear most of this this subreddit has never programmed for a living. Who is paying you to waste time providing exactly zero real benefit?

1

u/cajuncoding Sep 25 '20

“Don’t. Touch. Working. Code.”....

Ha, that’s Terrible advice as a mantra! In some contexts sure....but as a general mantra its contradicted by almost all well respected speakers/authors on software.

By that assertion, none of this subreddit code that pass tests should ever be improved?

Sure minimize risk but the mantra of never touch working code will amount to you (or the next person) inheriting technical debt the size of the USA deficit!

Instead. Pay. Your. Debt. Early. and. Reap. The. Rewards.

2

u/GavinZac Sep 26 '20

Self-contained code that has the right output is not technical debt. If nobody ever needs to look at the code again, making it pretty but slower is nothing but negative, and wasted time that could be spent on productive work, and is risk introduced for nothing but narcissism.

Technical debt is failing to maintain upgradeable functionality, deprecated features, cludging two non-working pieces together with a working bit, fragile code that 'mostly works', poor UI that 'just takes a bit of learning', insecure code that 'probably is fine', and missing edge cases that 'we'll get to some day'. It is not working implementations of very simple functionality that could have been done better but are done.

1

u/cajuncoding Sep 26 '20 edited Sep 26 '20

I’m not necessarily disagreeing with your last comment as it’s a much more detailed context - which explains your perspective and is also not contradictory to mine either.

However it’s become clearly confusing as to whether you are now talking about the original code in this thread or the code vaguely described by u/dam4rus?

Your response outlines many assumptions about code, none-of-which can we safely know about either this original post or the code described by u/dam4rus.

We cannot know if it’s self contained or encapsulated (which is one way to effectively mitigate the sprawl of such tech debt.)... nor do we know that no one ever needs to look at it again (which is very unlikely given that is some part of some file parsing logic that will almost certainly need to be improved or change in the future), nor do we know anything about the size of the input text/document (so I’d find it hard pressed to think that an alternative implementation would make this slower than iterating it completely 10 times), nor does making it easier to read (as you stated prettier) in any way enforce that it is slower or a useless change (it might have been useful for many other reasons). Perhaps the reason for change was because a new edge case was identified so now someone had to look at it again...perhaps another junior dev saw it and copy/pasted it into multiple places (yeah it happens all the time) and so as technical debt it just compounded by establishing a pattern that others will invariably follow...

So disregarding assertions that we don’t know about either code, it’s highly likely that both code fall into one or more of the criteria you outlined in your second paragraph (aka Tech Debt, needing to be cleaned up before someone thinks it’s ok to keep doing it this way).

Anyhow u/GavinZac, it feels like you may be arguing for the sake of it....therefore I’ll leave this dialogue like you’d leave this code....quick & dirty and never look back, the next person can clean up the mess (yeah I also deal with that type of mentality programmer at my current client too)!

1

u/GavinZac Sep 26 '20

To clarify my assumption since you asked: Almost anything that can be replaced by a simple regex is either a string replace or a string match. By their nature it is one argument in, one result out. Perfectly testable; perfectly self-contained.

Enjoy your day.

25

u/RavynousHunter Sep 21 '20

I mean, I can kinda get where they're coming from, personally. Regexes are naturally hard as hell to read, seein' as how it looks like someone's attempt at obfuscated Brainfuck. Then, there's that whole "greedy by default" that has caught me unawares more than a few times. I can totally understand wanting to just get the damn job done in a way that's legible (if not...ideal) and easy to understand.

11

u/new2bay Sep 21 '20

Exactly. If this code worked without literally creating a temporary string object for every ‘.replace()’ call, then I would think it was totally fine.

7

u/Beowuwlf Sep 21 '20

Best solution: make a replaceMultiple() function

12

u/new2bay Sep 21 '20

Well, that basically already exists in Python as string.translate().

4

u/Beowuwlf Sep 21 '20

Ah. I don’t use python so I didn’t know

3

u/[deleted] Sep 21 '20

Huh, TIL

3

u/RavynousHunter Sep 21 '20

Mmhm. There's a reason I avoid regexes for all but the simplest of tasks; they're oftentimes just...not worth the damned effort of debugging them.

1

u/cajuncoding Sep 25 '20

and iterating the entire string 10 times.... Sure if it wasn't full of code smell it'd be fine, but yeah it is pretty smelly, so it's not fine.

72

u/Space_Pirate_R Sep 21 '20

Well... there is the saying: "You have a problem. You decide to solve it using a regular expression. Now you have two problems."

1

u/brakkum Sep 22 '20

Except that’s people who don’t understand the appropriate use cases of regex

79

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Sep 21 '20

Image Transcription: Code


for words in user_file:
    get_word = words.replace("-", " ").lower().split()
    for word in get_word:
        user_words.add(word.replace('.', '').replace(',', '').replace('!', '').replace('?', '').replace(':', '')
                          .replace(';', '').replace('\"', '').replace('-', '').replace('[', '').replace(']', ''))

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

50

u/Ahajha1177 Sep 21 '20

Good human

2

u/trevhcs Sep 21 '20

Yeah, some bots...sorry "people bots" must be very dedicated to Reddit users!

17

u/_Kiiler_UwU Sep 21 '20 edited Sep 21 '20

badTokens = ["!","$"...]
newStr = "''.join(c for c in myString if not c in badTokens)

fuck Regex, all my homies use competitive knowledge

8

u/Jonno_FTW shameless Sep 21 '20

List lookups are slow, use a set, or better yet, use translate. https://docs.python.org/3/library/stdtypes.html#str.translate

3

u/CodenameLambda shameless Sep 21 '20

In my experience (though I might just not remember some variables to it) sets are slower when you're only dealing with a few elements.

I'm apparently misremembering (or something has changed):

Some quick tests gave me these timings for three characters to delete (via python3 -m timeit -s "setup code" -n 1000000 -r 5 "test expression):

.translate: 626 nsec
.replace: 208 nsec
re.sub: 1.59 usec
.sub with a compiled regex: 1.13 usec
predefined list (like in _Kiiler_UwU's comment): 4.08 usec
inline list: 3.9 usec, weirdly enough
predefined set: 2.52 usec
inline set: 2.43 usec (I think Python might be optimizing behind the scenes to some degree or something)
predefined string: 2.46 usec
inline string: 2.41 usec

Honestly those findings kind of make sense too - the iterator solutions all have the iteration in Python, while regex, .translate and .replace are probably implemented in C; where .translate has to deal with many different types plus the overhead of a hashmap while .replace only deals with single strings; while the regex solution has to deal with all the stuff regex entails. Though this is of course just wild speculation on my part, and my tests might already be faulty.

3

u/AutoModerator Sep 21 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/_Kiiler_UwU, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

48

u/moekakiryu Sep 21 '20 edited Sep 21 '20

In case anyone's wondering, here's the timeit results of regex vs replace (tl;dr string.replace is WAY faster)

Function Definitions: (imports implied)

def stringReplace(s,old,new):
    for c in old:
	    s=s.replace(c,new)
    return s

def reReplace(s,old,new):
    return re.sub("["+old+"]",new,s)

Each function was called 500,000 times using timeit.repeat, with s being a random 100 letter string, old being a random 5 letter string, and new being an empty string.

EDIT 3: As pointed out in another comment, this is not a fair test since the old string is regenerated every time, but is constant in the original post. This test is a more realistic solution to the problem

Results:

stringReplace:reReplace:
Mean:9.48s16.29s
Best:9.44s16.21s
Worst:9.55s16.34s

(5x100,000 iterations per test, all times are per 100,000 iterations)


EDIT: all da formatting

EDIT 2: fixed table alignment

24

u/Nall-ohki Sep 21 '20

This test is different than the given problem.

In the original, the replacements are static, and could benefit from re.compile() on a static var

14

u/moekakiryu Sep 21 '20 edited Sep 21 '20

perfect timing! You are absolutely correct! I was just writing the results of the additional test using re.compile. With a more fair test, they ended up being comparable but see my note at the bottom.

Function Definitions:

(stringReplace is same as above)

def compiledReplace(s,oldPattern,new):
        return re.sub(oldPattern,new,s)

randomChars = ''.join(random.choice(string.ascii_letters) for i in range(5))
randomPattern = re.compile("["+randomChars+"]")

I ran the test again with the same parameters as before, but using randomChars for stringReplace and randomPattern for compiledReplace

Results:

stringReplace:compiledReplace:
Mean:14.38s14.44s
Best:13.07s12.99s
Worst:16.07s16.50s

(5x100,000 iterations per test, all times are per 100,000 iterations)

I did have another program running in the background which resulted in slightly slower operating times overall, but the conditions did not change between the two tests.


So yeah, under perfectly optimal conditions for regex it breaks even with string.replace but it does suffer from readability concerns from needing to escape special characters and is slower if the search pattern changes on each iteration (which was rightly pointed out is not the case in the original post).

edit: typo

10

u/Nall-ohki Sep 21 '20 edited Sep 24 '20

That's to be expected - replace is a single purpose algorithm that's optimized for its case whereas regex is generally a compiled nondeterministic finite automaton (fast) or a tree parsed by a recursive descent parser (slow), though other approaches are possible.

The fact that it's that close in speed for being its own general sub language is pretty damn impressive as a technology.

I've written a niche special-purpose parsing system inspired by regex design during my first Masters, and it's amazing how useful having a less powerful language embedded gives you the ability to structure problems well while still being efficient.

Honestly, I think we'd benefit from language-level encoding of regex as opposed to string encoding in a lot of cases for readability.

1

u/christian-mann Sep 21 '20

Can you use a compiled NFA for regex replace?

1

u/Nall-ohki Sep 24 '20

Absolutely

2

u/RFC793 Sep 22 '20 edited Sep 22 '20

I wanted to test 2 other implementations, and I was concerned how much the random number generation is affecting the measurements. This code generates 100,000 random strings prior to testing. This list is cycled through for each iteration of each implementation. I had to do over 1 million iterations to get usable durations.

Code:

#!/usr/bin/env python3
import itertools
import random
import re
import string
import timeit

bad_chars = '.,!?:;\-[]'
bad_char_set = set(bad_chars)
bad_re = re.compile(r'[.,!?:;\\\-\[\]]')
bad_trans = str.maketrans('', '', bad_chars)

iters = 5 * (10**6)
repeat = 5

def str_replace():
    s = next(inputs)
    for c in bad_chars:
      s = s.replace(c, '')
    return s

def re_sub():
    return bad_re.sub('', next(inputs))

def str_translate():
    return next(inputs).translate(bad_trans)

def join_generator():
    return ''.join(c for c in next(inputs) if c not in bad_char_set)
    
def random_str(length):
    return ''.join(random.choices(string.printable, k=length))

print("Generating inputs...")
random_strs = [random_str(50) for x in range(100000)]

inputs = itertools.cycle(random_strs)
for fun in str_replace, re_sub, str_translate, join_generator:    
    print(f"{fun.__name__:16s}", end='', flush=True)
    results = timeit.repeat(stmt=fun, number=iters, repeat=repeat)
    print(f"min: {min(results):.4f}, max: {max(results):.4f}, avg: {sum(results)/len(results):.4f}")

Output:

str_replace     min: 8.9091,  max: 9.0107,  avg: 8.9448
re_sub          min: 7.5655,  max: 7.6123,  avg: 7.5922
str_translate   min: 12.6937, max: 13.2049, avg: 12.8160
join_generator  min: 20.8355, max: 21.3530, avg: 21.0275

I surely thought str.translate would be the fastest. It is purpose-built, and not as computationally complex as regular expressions. Boy was I wrong.

1

u/AutoModerator Sep 22 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/RFC793, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

10

u/[deleted] Sep 21 '20

Thanks. I learned from this

8

u/Jonno_FTW shameless Sep 21 '20

Try string.translate, it avoids the overhead of a loop:

t = str.maketrans({c:"" for c in ".,!?:;\"-[]"})
def replace(s):
    return s.translate(t)

10

u/moekakiryu Sep 21 '20

Your wish is my command:

stringReplace:translateReplace:
Mean:9.69s9.56s
Best:9.62s9.46s
Worst:9.78s9.64s

(5x100,000 iterations per test, all times are per 100,000 iterations)

This definitely looks faster. Since this test is relatively small, its possible string.translate could be faster for larger problems, but tbh I'm all tested out and don't really feel like looking into it. Nice solution all the same!! I'll have to remember this one

4

u/Jonno_FTW shameless Sep 21 '20

If you ever do codewars most of the solutions will use it as part of one liners (where required).

3

u/anamorphism Sep 21 '20

assuming all punctuation is to be replaced: s.translate(None, string.punctuation)

1

u/CodenameLambda shameless Sep 21 '20

Why the None,?

EDIT: Nvm, it appears to be a python2 thing, where the second argument is the list of characters to remove, if I'm not mistaken

1

u/RFC793 Sep 22 '20 edited Sep 22 '20

I thought the same and tested it. Interestingly, it is quite slow: https://reddit.com/r/badcode/comments/iwxm89/_/g66s11g/?context=1

2

u/Mr2-1782Man Sep 21 '20

Should point out that this is valid for only very simple constant to constant string replacements. Any variability will give regex the edge.

11

u/QFTornotQFT Sep 21 '20

11

u/xjcl Sep 21 '20

Oh, this one is very bad. The top 3 answers are using Python 2 syntax that won't work in Python 3.

4

u/Cometguy7 Sep 21 '20

For the first time, python (ok, python 2) has a feature of which I am jealous.

5

u/Chunderscore Sep 21 '20

Out of interest, what do you usually use?

1

u/Cometguy7 Sep 21 '20

Mainly C#. And if anyone's about to start bashing on C#, I don't really care, as it's an enterprise decision, not mine. Python has plenty of interesting things about it, this is simply the first I've seen where I said, man, I wish I had that.

3

u/TinyBreadBigMouth Sep 21 '20

str.translate is still available in Python 3, the interface just changed a little.

translation_table = str.maketrans('', '', '.,!?:;"-[]')
print(text.translate(translation_table))

https://docs.python.org/3/library/stdtypes.html#str.translate

29

u/KookyWrangler Sep 21 '20

Honestly might be more maintainable.

15

u/sendvo Sep 21 '20

how is this mess more maintainable than a single regex replace call?

11

u/xjcl Sep 21 '20

Regexes are too powerful and can introduce subtle bugs. Java has this problem with their String#split method which takes a regex String. So while in Python '8.8..'.split('.') == ['8', '8', '', ''], in Java you have to doubly escape the dot using "8.8..".split("\\."), EXCEPT that will result in a String[] of length 2 rather than 4, so you ACTUALLY have to do "8.8..".split("\\.", -1).

Another example:

    >>> import re
    >>> re.findall('\(.*\)', 'whitespace bad (haha) (not really)')
    ['(haha) (not really)']

It is not obvious how to fix this:

    >>> re.findall("\(.*?\)", 'whitespace bad (haha) (not really)')
    ['(haha)', '(not really)']

1

u/Mr2-1782Man Sep 21 '20

That's just an example of not understanding what you really want. Both results are valid, if you want to match everything but a specific character it would be more obvious to actually write that.

>>> re.findall("\([^()]+\)", 'whitespace bad (haha) (not really)')
['(haha)', '(not really)']

36

u/KookyWrangler Sep 21 '20

It's perfectly obvious what every step does and it's easily scalable. Poorly written regex would be worse.

17

u/chunes Sep 21 '20

I'm curious what you mean by scalable.

Doesn't each additional replace() call iterate over the entire string?

10

u/Ahajha1177 Sep 21 '20

He never said it was fast, just that it's very obvious what's going on.

6

u/moekakiryu Sep 21 '20

fwiw, string.replace is faster than re.sub (I commented the test results lower in this thread)

3

u/KookyWrangler Sep 21 '20

If you need something else, you can just add another replace().

5

u/Not_Sugden Sep 21 '20

i mean a regex is easy too, infact easier no? just add the character you want to the regex, 1 (maybe 2 if it needs escaping) key press, vs typing out .replace("...", "");

4

u/Qesa Sep 21 '20 edited Sep 21 '20

yes, word.replace('/[.,!?:;\"-\[\]]/g','') is a true mystery that nobody can discern

EDIT: Or since it's python and re.escape exists, word.replace('/[' + re.escape('.,!?:;"-[]') + ']/g','')

8

u/KookyWrangler Sep 21 '20

That's not how replace() works.

9

u/Qesa Sep 21 '20

Ah damnit that's the javascript usage. My python's rusty.

2

u/KookyWrangler Sep 21 '20

It's also better to use f-strings instead of re.escape.

2

u/Jonno_FTW shameless Sep 21 '20

Python has re.sub and the r string, so the call would be re.sub(r'[.,!?:;"-\[\]]', '', word)

1

u/Qesa Sep 21 '20

Yeah I am actually aware of that, just haven't used python in a couple of years but have been doing a decent bit of web work recently, so with all the replaces in the OP my brain entered js mode.

2

u/Jonno_FTW shameless Sep 21 '20

Some people simply might not be aware that it exists.

4

u/Terrain2 Sep 21 '20

why are they escaping the doublequote when its a singlequoted string

24

u/wampastompah Sep 21 '20

Honestly? I've done this before. It's certainly less efficient than regex, no one will deny that. But it's a hell of a lot more readable and maintainable, and it's less error prone. You'd be amazed how many people are out there who don't know or are uncomfortable using regex. If you have those people in your code base, something like this can prevent hours of headaches in the future.

6

u/FistThePooper6969 Sep 21 '20

Regex is less code, but way less efficient than string operations in terms of performance

5

u/wampastompah Sep 21 '20

Less code != More readable and maintainable. We're past the days when you had to limit the length of your code and variables, and usually things that are too short can be harder to read. Look at most Code Golf examples.

And performance depends on the situation. In Python, Regexes need to be created and compiled, which adds some overhead, but you only have to loop through the string once. In the case where there's only one word ten million characters long, a regex is way more efficient than looping through looking for each character one at a time. But in a realistic scenario with a couple hundred average english words, it really doesn't matter much.

2

u/Ultraflame4 Sep 21 '20

what is regex. I also thought it had something todo with registeries. It sounds complicated. plz teach

5

u/MysticTheMeeM Sep 21 '20

You might be thinking of RegEd a common abbreviation for Windows registry editor.

3

u/[deleted] Sep 21 '20

Kids these days.... Real men parse html with regex 😉😉

4

u/gregrainman314 Sep 21 '20

HTML and regex go together like love, marriage, and ritual infanticide.

4

u/[deleted] Sep 21 '20

Been there... Done that!

4

u/Needleroozer Sep 21 '20

Programmer: I have a problem.

Co-worker: Use RegEx.

Programmer: Now I have five problems.

2

u/[deleted] Oct 05 '20

Regex is scary

1

u/u--x Sep 21 '20

Fuck Regex, all my homies use their own made DFSAs.

1

u/omegasome Sep 22 '20

At the very fucking least just put your replacements in a list and use a FOR loop:

for c in bad_characters:
    word = word.replace(c, '')
user_words.add(word)

-1

u/Th3T3chn0R3dd1t Sep 21 '20

Dont see how regex would help - granted this is needlessly long but regex replacement would be even longer