views:

96

answers:

3

Is there a singular regular expression that can be used in, say, a text editor's search/replace dialog to reverse the order of the items in a list?

For instance, take this list:

  • First item
  • Second item
  • Third item

Select it in a text editor like EditPad, bring up the search and replace box, apply a regex (run as a loop or not) and turn it into:

  • Third item
  • Second item
  • First item

Can this be done?

+4  A: 

This cannot be done by a regular expression.

I'd recommend using a language like Perl, where you can use a regular expression to split the list and write it back in reversed order.

Charles
A: 

Not technically regular expressions, but there's a sed one-liner that reverses the lines of input (source):

sed '1!G;h;$!d'

and a vi command to reverse the lines of the current file (source):

:g/.*/m0
Joey Adams
+1  A: 

Only if the list has a fixed, known number n of items, and even then the regexp gets more complicated as n grows. (The main difficulty is usually to get a literal newline into the engine.)

It is possible to generate this series of increasingly complex regexes quite easily with a scripting language; however, once you use a scripting language, it is almost certainly easier to use it for the reversing itself!

Kilian Foth