tags:

views:

391

answers:

6

Can anyone help me with a regex to turn:

filename_author

to

author_filename

I am using MS Word 2003 and am trying to do this with Word's Find-and-Replace. I've tried the use wildcards feature but haven't had any luck.

Am I only going to be able to do it programmatically?

+12  A: 

Here is the regex:

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

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 is a Python example:

from re import sub

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


Edit: In order to do this in Microsoft Word using wildcards use this as a search string:

(<*>)_(<*>)

and replace with this:

\2_\1

Also, please see Add power to Word searches with regular expressions for an explanation of the syntax I have used above:

  • The asterisk (*) returns all the text in the word.
  • The less than and greater than symbols (< >) mark the start and end of each word, respectively. They ensure that the search returns a single word.
  • The parentheses and the space between them divide the words into distinct groups: (first word) (second word). The parentheses also indicate the order in which you want search to evaluate each expression.
Andrew Hare
I might have to do this in code I guess. Do you know what I would need, if I have to replace the second part with a fixed text like "myname_filename"?
Joan Venge
Thanks. This did the trick.
Joan Venge
+2  A: 

Here you go:

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

Depending on the context, that might be a little greedy.

moshen
+1  A: 

In .NET you could use ([^_]+)_([^_]+) as the regex and then $2_$1 as the substitution pattern, for this very specific type of case. If you need more than 2 parts it gets a lot more complicated.

John M Gant
As others have noted, (.*) would be better for the second part of the regex than ([^_]+).
John M Gant
+2  A: 

Search pattern:

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

Replacement pattern:

$2_$1
ceejayoz
A: 

In C# you could also do something like this.

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

You asked about regex of course, but this might be a good alternative.

John M Gant
+1  A: 

Since you're in MS Word, you might try a non-programming approach. Highlight all of the text, select Table -> Convert -> Text to Table. Set the number of columns at 2. Choose Separate Text At, select the Other radio, and enter an _. That will give you a table. Switch the two columns. Then convert the table back to text using the _ again.

Or you could copy the whole thing to Excel, construct a formula to split and rejoin the text and then copy and paste that back to Word. Either would work.

John M Gant