Pattern Replace (3)

Regular Expressions (grep) let you do find and replace by pattern, eg swapping the order of words in a list. It’s a powerful technique and not as hard as you may think. Here’s the third of 3 articles.

 

Pattern Replace (3)
Mac Tip #269/15-Nov-2006

Recent Tips have shown how to switch a pair of names using grep in Tex-Edit Plus and Microsoft Word. Please read those Tips again to refresh your memory of what’s going on. We used a regular expression to switch around names

This time we do a similar thing with TextWrangler, a free text editor from BareBones.

The reason for doing the same task in three different applications is to show that the fundamentals are the same, or similar, for each program, although details may vary. Moreover, different programs may offer slightly different grep features.

For example, TextWrangler has a ‘word boundary’ feature that we use this week to find ‘words’ rather than just ‘groups of letters’.

Download TextWrangler and paste in a list of reversed names:

  • Janeway, Kathryn
  • Summers, Buffy
  • Carter, Samantha
  • Torres, B’Elanna

Search

Press Command F to call up the Find and Replace dialog box and be sure to check the Use Grep checkbox.

The word boundary

TextWrangler allows us to look for a word boundary, and that’s just what we want: one word followed by a comma and space and then another word. The word boundary (\b) lets us construct a search to find any number of characters (.+) within the bounds of a word:

Search for: (\b.+\b), (\b.+\b)

Replace with: \2 \1

Click the Replace All button to switch the reversed names around to the first-last order we require. TextWrangler flashes up an alert to advise you that it has made the replacements.

This Regular Expression handles the apostrophe in a name without problems.

Next week: More Find and Replace tips

Thanks for reading. Remember to tell your friends about MacTips. Subscribe for regular Tips.

Clip to Evernote

Tell us what you think.
Note: your comment is not published straight away. I check and approve all comments, otherwise the spammers get a free rein. I usually check comments within 24 hours.

Add your Comment

Take Control ebooks (affiliate link) are superb.
I do some of my best learning from them. Buy through my link so I can make more and better Tips.

Take Control of Using Lion.   Buy Take Control of iCloud.  Macworld iPhone 4S Superguide   Take Control of iTunes 10: The FAQ, Second Edition