Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl one-liner to match all occurrences of regex

Tags:

regex

perl

For multiple lines of text similar to this:

"views_panes","gw_hero_small_site_placement-panel_pane_1",1,"a:0:{}","a:10:{s:14:\"override_title\";i:1;s:19:\"override_title_text\";s:0:\"\";s:9:\"view_mode\";s:11:\"all_purpose\";s:11:\"image_style\";s:7:\"default\";s:13:\"style_options\";a:2:{s:10:\"show_image\";i:0;s:9:\"show_date\";i:0;}s:18:\"gw_display_options\";s:22:\"gw_all_purpose_sidebar\";s:13:\"show_readmore\";a:1:{s:18:\"show_readmore_link\";i:0;}s:14:\"readmore_title\";s:9:\"Read more\";s:13:\"readmore_link\";s:0:\"\";s:7:\"exposed\";a:1:{s:23:\"field_hero_sub_type_tid\";s:3:\"547\";}}","a:0:{}","a:1:{s:8:\"settings\";N;}","a:0:{}","a:0:{}",0,"s:0:\"\";"

I am looking to match all instances of (s:)(\d{1,}:)\"(string)\"; to get something like this:

s:14:override_title
s:18:show_readmore_link
s:3:547

This line with or without /g prints only the first instances:

perl -nle 'print  "$1 $2 $3"  if /(s:)(\d{1,}:)\\"(.*?)\\";/g' tmp.txt

s:14:override_title

I suppose I can try to put this in a perl script putting all matches into an array, but am hoping to do this using a one-liner (-: What am I missing?

Mac OS X 10.7.5, perl 5.12.3.

like image 478
KM. Avatar asked Sep 26 '13 14:09

KM.


People also ask

What is \b in Perl regex?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length.

Is Perl good for regex?

In general, Perl uses a backtrack regex engine. Such an engine is flexible, easy to implement and very fast on a subset of regex. However, for other types of regex, for example when there is the | operator, it may become very slow.

What does (? I do in regex?

E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.

How do I match a new line in a regular expression in Perl?

Use /m , /s , or both as pattern modifiers. /s lets . match newline (normally it doesn't). If the string had more than one line in it, then /foo. *bar/s could match a "foo" on one line and a "bar" on a following line.


1 Answers

It's seem you have only line, so have a try with:

perl -nle 'print  "$1 $2 $3"  while(/.*?(s:)(\d{1,}:)\\"(.*?)\\";/g)' tmp.txt
like image 119
Toto Avatar answered Sep 20 '22 16:09

Toto