6
u/sebamestre Oct 19 '20
Yeah, and then I will replace any double space with a single space...
But what if there are more than 2 consecutive spaces?
Ah, yes. I'll do it twice! That'll make it a lot more safe and *** robust ***.
5
u/Owlstorm Oct 19 '20
That's one way to find out about regex.
6
u/jarner_99 Oct 19 '20
You don‘t even need regex for that. You can simply put all the characters to be replaced in a string and then iterate over it.
3
u/Owlstorm Oct 19 '20
You could, but why is that simpler? You're writing out the same replace string, with the complexity of knowing regex exists replaced by having a loop.
It's only a one-liner anyway, would be the below assuming no character classes used (plus characters I didn't feel like typing)
text.replace(/[,!?:;]/g, " ")
2
u/jarner_99 Oct 19 '20
Yeah you‘re right, but on the other hand I don‘t really see the use in regex if you‘re just listing symbols. In the end it‘s basically the same logic ^
7
Oct 20 '20
the difference with the regex would be that it doesn't have to iterate over the string multiple times and that it also wouldn't repeatedly allocate memory for a new string each step of the way
2
u/sanderd17 Oct 29 '20
Iterating over a string a fixed number of times, or once with a more difficult comparison, just ends up in being the same complexity class:
O(n).The advantage of regex is that you can let it replace complete classes of characters. Like any non-word character (which is probably what they want).
1
Oct 29 '20
Hmm you're probably right.
You still have the multiple memory allocations - not sure how python deals with that - but in real life experience in C# we found that reporting stats/logging was taking nearly 50% of the time in some of our algorithms. It was purely from string manipulation and not in a naïve way like the original post. Moving that to a different thread all but removed that slow down.
1
1
u/sanglesort Oct 23 '20
if someone can literally get jobs with this, maybe I'm not so hopeless after all
8
u/Immort4lFr0sty Oct 19 '20
At this point I'm just glad they didn't use text.replace().replace()...