Is there a way to search for a pattern in a MS Word document?
like 'N/M' within a word document, where N denotes a decimal and M also shows another decimal number
Just for a search you can use ^#/^#
as your search parameter. Under the more options, and find Special, there are some other options that can be helpfull.
Nb: ^#
, is one decimal place so if you are looking specifically for x/yy then it would be ^#/^#^#
etc.
to Replace,
This is a better option , perform search with ([0-9])/([0-9])
and replace with \1.\2
, and enable "use wildcards"
Word
Use Microsoft's implementation of regular expressions
Press CTRL+H » click on More » Enable Use wildcards
- Find what:
([0-9]{1,2})/([0-9]{2})
- Replace with:
\1.\2
This looks like a crazy search pattern so let's examine it:
-
[0-9]
stands for a single numeric value (0,1,2,3,4,5,6,7,8 and 9) -
{1,2}
is used for counting occurrences of the previous character or expression. In our case this means: Search only for one or two numerics.Caution: If you're using a german Word, you have to use
;
as separator instead of,
-
/
has no special meaning. It literally searches a slash -
()
the round brackets are important. They divide the pattern into logical sequences so we can later use\1
,\2
...\n
in our replace pattern. This way we preserve values
Read more on the section The expressions, Piece by piece in Microsoft's support article or on Graham Mayor's Word site
VBA (better solution)
I suggest you to use a VBA method which adheres more to the default from other RegEx engines. They are better documented and more people can help you.
This macro asks for a RegEx pattern to search in the whole document and replace it with your given string.
Press ALT+F11 to open the VBA editor. Paste the code anywhere and execute it with F5
Sub RegexReplace()
Dim RegEx As Object
Set RegEx = CreateObject("VBScript.RegExp")
On Error Resume Next
RegEx.Global = True
RegEx.Pattern = InputBox("Find what:")
ActiveDocument.Range = _
RegEx.Replace(ActiveDocument.Range, InputBox("Replace with:"))
End Sub
- Find what:
(?!\d)/(?=\d)
- Replace with:
.