4 ms·
I've finally decided that regular expressions are not witchcraft and that I need to learn how to use them.
by MarcScott 12y ago
I've finally decided that regular expressions are not witchcraft and that I need to learn how to use them.
- kelukelugames 12y agoI spent an entire day trying to decipher how to replace spaces with tabs. Wish I had been better with regular expressions.
- gknoy 12y agoI hope this isn't flippant, but have you read the Perl regex man pages [0]? "Perl compatible" regexes are very common, and are explained _really_ well. Similarly, the Perl Cookbook (from O'Reilly) has a whole chapter on regular expressions -- even crazy ones like detecting US phone numbers (hard!) -- with explanations. That chapter is QUITE good, and I highly recommend it even you don't write Perl. For your specific problem at hand, I assume you want to replace spaces with a tab character. In Perl, you could do: # replace four spaces with a tab, globally $line =~ s/ /\t/g; You can do this directly on the command line as well: perl -e 'while (<>) { $line = $_; $line =~ s/ /\t/g; print $line; }' < foo_spaces.py > foo_tabs.py I have a gist [1] which has very slightly more comments, if you prefer. To paraphrase XKCD, there are now N+1 regex explanations, and I apologize that mine is comparatively worse than all of them. :) 0: http://perldoc.perl.org/perlre.html http://perldoc.perl.org/perlre.html 1: https://gist.github.com/gknoy/94c382299c4543f2e863 https://gist.github.com/gknoy/94c382299c4543f2e863
- kelukelugames 12y agoThanks for sharing the man page link. I am reading it now! :)
- deleted 12y ago[deleted]
- japhyr 12y agoHave you looked at sed yet?
- kelukelugames 12y agoSed was the problem. On Mac the syntax is slightly different and it doesn't take \t as tab. Those two curve balls took some extra research. I didn't actually take the entire day. :)
- mercnet 12y agoAny recommendations on learning them, e.g. tutorials?
- pc86 12y agoNot helpful at all for learning, but I've found RegExper[1] is fantastic for visualizing existing expressions, particularly ones you haven't written but need to understand or edit. [1] http://www.regexper.com/ http://www.regexper.com/
- tovmeod 12y agoI like http://www.debuggex.com/ http://www.debuggex.com/
- mdibaiee 12y agofor JavaScript devs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guid... also http://overapi.com/regex http://overapi.com/regex
- j13z 12y agoThis is also a great tool to play around with / construct regexes: http://regex101.com/ http://regex101.com/
- bbcbasic 12y agoTip: You don't have to put the entire expression in one line