Regex: replace words from a list of words

153 Views Asked by At

I am new to regex. I use an Android text editor with regex feature for search and replace. The application has dialog for search string and replacement string. It works wonderfully.

I have a list of 10 words with 10 words for replacement. Can regex do the replacements in one go? For example, search for: (aa), (bb). Replace with: xx, yy. Thanks

As a newbie, I don't know where to start. But I have my PHP codes to do that if regex couldn't. I also know, a macro in Word could accomplish the task.

1

There are 1 best solutions below

1
Eddie On

I want to replace month in number to month name. E.g. 3 for March, 5 for May etc. After a lot of trial and error, I came up with this solution.

I read the text line by line. Add this to that line.

..1,Jan;2,Feb;3,Mar;4,Apr;5,May;6,Jun;7,Jul;8,Aug;9,Sep;10,Oct;11,Nov;12,Dc

Save.

Read the file again line per line. Search for that month in number. Fortunately, in my case, the place of the month is fixed. It is after the day. The format bring DD-MM-YY

I just search:

(\<div.+mid\"\>\d{1,2})\-(\d{1,2})\-(.+)(\<\/div\>).+?(?=\2)\d{1,2}, (\w+)

And replace with

$1 $5 $3$4

Explanation:

  1. Search for the month number:\-(\d{1,2})\- This is the second group captured.
  2. Make a lazy match with question mark..+?
  3. Find a match of the number of the month in group 2.(?=\2)
  4. Fetch the name of the month that is placed after that number. In this case, it is the \w÷. \d{1,2},(\w+)
  5. Done.

You may have to remove the trailing month names. Easy.