Regex replace string with another string in MS Word?

Can anyone help me with regex:

filename_author

      

to

author_filename

      

I am using MS Word 2003 and am trying to do this with Word Find-and-Replace. I tried the function use wildcards

but no luck.

Can I only do this programmatically?

+3


a source to share


6 answers


Here's a regular expression:

([^_]*)_(.*)

And here is a C # example:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        String test = "filename_author";
        String result = Regex.Replace(test, @"([^_]*)_(.*)", "$2_$1");
    }
}

      

Here's a Python example:

from re import sub

test = "filename_author";
result = sub('([^_]*)_(.*)', r'\2_\1', test)

      




Change: . To do this in Microsoft Word using wildcards, use this as a search string:

(<*>)_(<*>)

and replace with this:

\2_\1

Also, see Add Regular Expressions to Word Search for an explanation of the syntax I used above:

  • The asterisk (*) returns all text in a word.
  • Values ​​(<>) are less than and greater than the characters denoting the beginning and end of each word, respectively. They make sure the search returns one word.
  • Brackets and the space between them divide words into separate groups: (first word) (second word). The parentheses also indicate the order in which you want to search to evaluate each expression.
+14


a source


Here you go:

s/^([a-zA-Z]+)_([a-zA-Z]+)$/\2_\1/

      



Depending on the context, this can be a little greedy.

+2


a source


Search scheme:

([^_]+)_(.+)

      

Replacement scheme:

$2_$1

      

+2


a source


In .NET, you can use ([^_]+)_([^_]+)

as a regular expression and then $2_$1

as a replacement pattern for that special type. If you need more than two pieces, it gets much more complicated.

+1


a source


Since you are in MS Word, you can try non-programming. Select all of the text, choose Table → Convert → Text to Table. Set the number of columns to 2. Select "Split Text In", select "Other" as an amateur and enter "_". This will give you a table. Switch two columns. Then convert the table back to text with _ again.

Or you can copy it all into Excel, build a formula to split and rejoin the text, and then copy and paste it back into Word. Or everything will work.

+1


a source


In C #, you can also do something like this.

string[] parts = "filename_author".Split('_');
return parts[1] + "_" + parts[0];

      

Surely you asked about regex, but this might be a good alternative.

0


a source







All Articles