Showing posts with label regular expressions. Show all posts
Showing posts with label regular expressions. Show all posts

Saturday, October 26, 2019

Perl : Highlight Matches in String

That is, you have a string, and now, you have a bunch of patterns to match and, you now want to print the string with the matches highlighted. How/why?

Start with why so Simon don't cuss : You can use this to build your own personal search engine. Who needs to contend with the crappiness of Evernote?

How :

use Term::ANSIColor qw(:constants);
have your patterns in @regexes = ( 'string1', '\bword1\b', 'etc')

Then, (this one assumes all the items in @regexses will match. If that's not your data, put in an if :)

foreach $word ( @regexes ){
  $string =~ /^(.*?)($word)(.*?)$/;
  $string = $1 . UNDERLINE . $2 . RESET . $3;
}


Seem amateurish? :)

Thursday, March 22, 2018

How Useful is Perl's -l? It Depends

You want to generate

1
2
3
4
5

If you didn't know about -l, you might do

$ perl -e 'foreach (1..5) {print; print "\n";}'

But, if you knew about -l, you could do :

$ perl -le 'foreach (1..5) {print;}'

To accomplish the same thing. Moral - ... make up your own moral. But, never stop learning!!

Now, what if you wanted to pipe this through a script to produce just

1

One way is

| perl -n -e 'print and exit if /\d/;'

Works, but doesn't

| perl -n -e 'print if ?\d?;'

Look prettier? What is the ?? version of the match operator? Only match once!

Saturday, March 25, 2017

Python is Crap Compared to Perl

When it comes to text processing.

Okay, this is a known fact. Question - why hasn't this gotten more attention?

How would you do this?

string : "Mary had a little lamb1" --> "Mary had1 a little lamb" . Okay, a lame example - I want to append a 1 after a d or a b. In perl, it's as simple as s/([db])/${1}1/g . What is it in Python????

Here's a guy who barely scratches the surface. A valiant attempt though .. better half a loaf.

What is the equivalent of using curly braces for variable names within interpolated strings?????

Anyways, here's one way of accomplishing this particular task (Thanks!) :

re.sub( r"(?P)[db])" , r"\g1" , myString )

Enjoy..