Replace with function in word

01

Все кто когда-либо сталкивался с подстановочными символами (Wildcards) знают, что это достаточно убогая попытка реализовать в VBA механизм подобный регулярным выражениям в других более развитых языках. Помимо более скудных возможностей (я уже не говорю о невозможности указания количества «ноль-или-один») данный механизм также ограничен и в сложности выстраиваемых выражений, и те кто пытался решить более-менее сложные задачи не раз сталкивался с ошибкой Поле «Найти» содержит слишком сложное выражение с использованием подстановочных символов. Отсюда и возникла необходимость воспользоваться более могущественным инструментом — регулярными выражениями.

02 VBA

1
2
3
4
5
6
7
8
9
10
11

Dim objRegExp, matches, match

Set objRegExp = CreateObject(«VBScript.RegExp»)

With objRegExp
.Global = True
.IgnoreCase = False
.pattern = «pattern»
End With

03

Здесь, конечно, каждый кодер обрадуется — вызываем Replace и все ок!

04 VBA

1

Set matches = objRegExp.Replace(ActiveDocument.Content, «replacementstring»)

05

Но при запуске, конечно же, будет выдана ошибка. Это связано с тем, что метод Replace объекта VBScript.RegExp принимает на вход первым параметром строковую переменную, а не объект (в нашем случае ActiveDocument.Content), и возвращает этот метод также измененную строку, а не вносит изменение во входящую, отсюда и танцы с бубнами:

06 VBA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Set matches = objRegExp.Execute(ActiveDocument.Content)

For Each match In matches
Set matchRange = ActiveDocument.Content
With matchRange.Find
.Text = match.Value
.Replacement.Text = «replacementstring»
.MatchWholeWord = True
.MatchCase = True
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.Execute Replace:=wdReplaceOne
End With
Next

07

Ну хорошо, скажете вы, ну а если нам нужно переформатировать данные по аналогии с выражениями типа $1-$3-$2 (т. н. «обратные ссылки» в регулярных выражениях), т. е. как к примеру из 926-5562214 получить +7 (926) 556-22-14. Это тоже достаточно просто, здесь они тоже есть — единственное отличие — нумерация найденных групп начинается не с нуля, а единицы — $1. Давайте пока отвлечемся от нашего документа и посмотрим как это можно сделать с обычной строковой переменной:

08 VBA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

19

Dim objRegExp, matches, match

Set objRegExp = CreateObject(«VBScript.RegExp»)

Dim strSearch As String
Dim strResult As String
strSearch = «Пусть у нас есть несколько телефонов 8495-3584512, 8800-4852620 и, к примеру, 8950-5628585»

With objRegExp
.Global = True
.IgnoreCase = False

.pattern = «8(d{3})-(d{3})(d{2})(d{2})»

End With

strResult = objRegExp.Replace(strSearch, «+7 ($1) $2-$3-$4»)

Debug.Print strResult

09 На заметку:

12 строка выделена для того чтобы подчеркнуть каким образом было разделено указание на подгруппы ($2, $3 и $4), ведь выражение (d{3})(d{2})(d{2}) эквивалентно (d{7}). Но во втором случае, рекурсивный запрос содержал бы все 7 цифр.

Изучайте регулярные выражения!

10

Но поскольку, как уже говорилось выше, вместо входной строки у нас объект ActiveDocument.Content, такой метод не подойдет для работы. Придется пойти на хитрость — объединить два предыдущих кода:

11 VBA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

Set objRegExp = CreateObject(«VBScript.RegExp»)

With objRegExp
.Global = True
.IgnoreCase = False
.pattern = «8(d{3})-(d{3})(d{2})(d{2})»
End With

Set matches = objRegExp.Execute(ActiveDocument.Content)

Dim strReplacement As String

For Each match In matches
Set matchRange = ActiveDocument.Content

strReplacement = objRegExp.Replace(match.Value, «+7 ($1) $2-$3-$4»)

With matchRange.Find
.Text = match.Value
.Replacement.Text = strReplacement
.MatchWholeWord = True
.MatchCase = True
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.Execute Replace:=wdReplaceOne
End With
Next

12

Оборачиваем в оболочку-функцию и, вуаля:

13 VBA

1

2
3
4

5

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

Sub ВыполнитьГруппуПреобразований_RegExp()
Call Выполнить_RegExp(«8(d{3})-(d{3})(d{2})(d{2})», «+7 ($1) $2-$3-$4»)

End Sub

Sub ВыполнитьГруппуПреобразований_RegExp() …

Private Sub Выполнить_RegExp(pattern As String, patternExpr As String)
Set objRegExp = CreateObject(«VBScript.RegExp»)

With objRegExp
.Global = True
.IgnoreCase = False
.pattern = pattern
End With

Set matches = objRegExp.Execute(ActiveDocument.Content)

Dim strReplacement As String

For Each match In matches
Set matchRange = ActiveDocument.Content

strReplacement = objRegExp.Replace(match.Value, patternExpr)

With matchRange.Find
.Text = match.Value
.Replacement.Text = strReplacement
.MatchWholeWord = True
.MatchCase = True
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.Execute Replace:=wdReplaceOne
End With
Next
End Sub

Private Sub Выполнить_RegExp(pattern As String, patternExpr As String) …

14

Нельзя умолчать о существовании, к сожалению, некоторых ограничений в синтаксисе регулярных выражений при использовании объекта VBScript.RegExp в VBA. Эти ограничения провоцируют ошибку Run-time error ‘5017’ Application-defined or object-defined error. Вот некоторые из них:

15
  • отсутствуют указатели на начало и конец текста A и Z — вместо этих указателей можно использовать указатель конца текста $;
  • отсутствуют назад- (?<=…) и впередсмотрящие (?=…) указатели (утверждения, lookbehind assertions), равно как и их отрицательные реализации — (?!=…) и (?!…);
  • отсутствует ряд модификаторов.
17

Похожие запросы:

  • Регулярные выражения в MS-Word
  • VBA regular expression, replacing groups
  • Поиск и замена текста с помощью объекта VBScript.RegExp
  • Замена текста в документе при помощи регулярных выражений
  • Regex Capture Groups and Back-References
  • Разработка регулярного выражения для разбора строки с помощью обратных ссылок

You’ve just finished typing a presentation that’s due in about 15 minutes. But before you can celebrate your moment of victory, you realize that you’ve spelled your client‘s name wrong and have missed the double Rs in their company name multiple times throughout your document.

Cue: An aggravated scream.

The good news is that changing these small errors is an easy fix on Office 365. You can replace as many words as you want within seconds on Microsoft Word using its super helpful Find and Replace functionality.

This article will guide you through the necessary steps to help you find and replace text in MS Word.

Ready? Let’s begin.

How to Use Microsoft Word’s Find and Replace Feature

Microsoft is one of the leading companies in the world. It’s because it prioritizes its customers and comes up with innovations that can make their lives easier and more convenient.

The Find and Replace feature on MS Word is a shining example of this effort.

You can use this feature to find specific words in your file and then replace them in case there are some last-minute changes. This can even be useful when you make mistakes in the doc while typing or want to accommodate those last-minute client changes.

We’ll show you how to replace text in Microsoft Word, depending on the computer device you use.

How to Change and Replace Text in MS Word on Windows

It’s no wonder that all Windows devices have built-in Microsoft programs considering it’s a product developed by the Microsoft company themselves. If you find yourself using the word processor often for making notes or presentations, you’ll be especially thankful for the Find and Replace functionality.

Here’s a short step-by-step guide to using the feature in MS Word on Windows devices:

Step #1 Open Microsoft Word on your Windows device.

Step #2 Click on the Home tab on your top menu bar. A secondary menu will appear on your screen.

Step #3 Select the Replace option located on the top-right-hand side of your screen. Alternatively, you can also press Ctrl + H. The Find and Replace pop-up box will appear immediately.

Step #4 Type in the phrase or word you want to locate in your Word doc in the Find what field under the Find tab.

Step #5 Click on the Replace tab on the top menu bar. Type in the word you want to update in the Replace with field.

On clicking on the Replace button, the changes you want will be made one by one in the Word doc. However, if you want to update all fitting instances at once, you can click on Replace All instead.

Microsoft Word will give you a confirmation of the replacements made in your Word doc. It’ll look something like this:

How to Change and Replace Text in MS Word on Mac

Now that we’ve covered Windows, let’s see how you can use the Find and Replace feature on a MacBook. Here’s how to proceed in MS Word when you’re using an iOS device:

Step #1 Open the Microsoft Word document on your Mac.

Step #2 Take your cursor towards the top of your screen until you see your Mac’s top toolbar. Click on the Edit tab. A dropdown menu will appear.

Step #3 Click on Find from the displayed menu options. You’ll typically see a Replace… option on your screen.

But if you don’t, simply press Shift + Command + H on your keyboard. A side navigation bar will appear on the left-hand side of your computer screen.

Step #4 Enter the word or phrase you want to replace in the doc in the Search for… field.

Once you’ve finished typing the incorrect word or phrase, type in the right word or phrase that you want to replace the incorrect one with in the Replace with… field.

Step #5 Click on the Find tab to locate the matches. Once you’re sure the match is right and highlighting the words you want to change, select Replace. This will replace every individual match one by one.

Again, if you click on the Replace All button, all the matching words and phrases will be changed at once.

After the changes are made, you’ll see an “All Done” message just below the Replace and Replace All buttons that indicate the replacement of the intended word or phrase.

Advanced Find and Replace Features: Everything You Need to Know

You can take this whole shebang of replacing words and phrases to the next level thanks to Microsoft Word’s Advanced Find and Replace option. In other words, you can use the Advanced settings to simplify the process further and make the results even more accurate.

Follow the previously stated steps to open the Find and Replace pop-up box. On it appears on your screen, click on More.

You’ll immediately see a slew of additional options like Match case, Use wildcards, Match prefix, Match suffix, and so on. Here’s how the Advanced Find and Replace settings look like:

Each one of these has its own unique functions. Let’s discuss them in more detail below:

Find whole words only

If you check on the Find whole words only box, MS Word will treat your search term as an entire word and won’t look for your search term within other words.

Example: If you’re searching for the word “stand,“ the search feature won’t show you the word “standard.”

Use wildcards

Use wildcards is one of the more advanced search options that allows you to use question marks, brackets, asterisks, and other similar symbols to modify your search.

You see, a wildcat is a short string of characters – or a character – that represents multiple characters in a search.

Example: <(int)*(net)>

Sounds like (English)

As the name suggests, the Sounds like option finds similar-sounding words to your search term. This is best for finding homonyms and words that have varying spellings.

Example: This is common for words that have both UK and US variants. For instance, you can have both “colours” and “colors” on a document.

Find all word forms (English)

This option allows you to look for the word you searched for, along with other instances that are either plural or in a different tense.

Example: If you search for the word “be” after enabling the Find all word forms option, you’ll also find the words “are“ and “is“ highlighted as they are the different tense forms of “be.”

Match prefix and Match suffix

Checking off the Match prefix or Match suffix fields will limit your search to words that have the same beginning or the same ending, respectively.

Example: Suppose you enable Match prefix. When you search for the word “love,” Microsoft Word will find the words “love“ and “lovely.“ However, you won’t find the word “beloved“ highlighted in the search results as it’s a suffix of love.

Ignore punctuation characters and Ignore white-space characters

Again, this search option is self-explanatory. It tells Microsoft Word not to take up spaces, periods, hyphens, and similar attitudes into consideration.

Example: After clicking on the search options, when you type in “color block”, you’ll also see “color-block.”

When to Use the Find and Replace Feature of Microsoft Word

The whole point of the Find and Replace function in Microsoft Word is to allow MS Word users to search for target text – whether it’s a specific word, a type of formatting, or a string of wildcard characters – and replace them with whatever you want.

Typically, here’s why you should use this feature:

  • When you want to maintain absolute consistency in your document
  • When you want to speed up typing and formatting tasks
  • When you realize last-minute mistakes and want to find and then replace your errors
  • When you’re writing a document that includes words with varying spellings. For instance, if you typically follow US English, and are typing a doc according to the rules of UK English, the Find and Replace feature would be super helpful to identify and change spelling errors.
  • Adding special characters to words
  • editing partial words and phrases
  • Correcting words that you may have misspelled in a hurry. For instance, if you type “h?t” instead of “hat” and enable Use wildcards, you’ll find it highlighted in your search.
  • Eliminating extra spaces
  • Changing the separator character in numerals
  • Reversing currency symbols

Concluding Thoughts

As you may have realized, the Find and Replace feature of Microsoft is a lifesaver, to say the least.

It can help you save tons of time, which would otherwise have been wasted in looking for errors and then replacing them. Whether you are a student, an intern, or the CEO of a company, this is a functionality that we all can be very thankful for.

Word Find and Replace

The Microsoft Word Find and Replace feature is very powerful and a great time saver for the more skilled user. You can use Find and Replace to locate exact words, phrases and even patterns matching various scenarios.

Let us start with exploring how to do a regular Find and Replace in Word.

Click the Find or Replace buttons in the Home ribbon Editing section

Find and Replace in Word - Replace Button
If you want to Find a word or sentence in your Word file go to the Home ribbon tab and go to the Editing section.

  • If you want to Find click Find
  • If you want to Find and Replace click Replace
  • This will open the Find and Replace window.

    You can also use the CTRL+F keyboard shortcut to Find and the CTRL+H keyboard shortcut to do a Find and Replace.

    If you click More > > you will see the full set of options below:
    Find and Replace expanded window
    The following options are available:

    • Match case – will only find words/sentences that match the letter case (e.g. A vs a)
    • Find whole words only – will only find whole words (if looking for “ate” will only match ” ate “ and not “late”)
    • Use wildcards – allows you to use wildcards (click the Special button for list of wildcard special characters that can be used
    • Sounds like – matches expressions that sound like provided text
    • Find all word forms – matches all words/sentences that match a word form (e.g. “doyle” will also match “doyl” as it sounds similar)
    • Match prefix – match text matching a prefix of a word
    • Match suffix – match text matching a suffixof a word
    • Ignore punctuation characters – will ignore punctionation
    • Ignore white-space characters – will ignore white-space (” “)

    Provide a word, sentence and/or wildcard special characters

    Provide a word/sentence you want to Find in the Find what text field and the word/sentence you want to replace it with in the Replace with text field.

    Below and explanation of key buttons used to Find or Replace text:
    Find and Replace fields explained
    Although Find and Replace is a basic and very easy to use function it is often underestimated. Especially that many users do not know that you can easily use wildcards to replace more complex text patterns.

    Using Wilcards

    Word Wildcard Special Characters
    You can also you wildcards to replace various complex patterns such as sequences of numbers or specific number of occurances, letter cases, characters use to replace any characters and much more. To use wilcards click More > > and select the Use wilcards checkbox.

    On the right you should see all available wildcard characters.

    For more information on Special Characters that can be used in Wildcard Find and Replace read this

    Let us explore some example common scenarios below:

    Match any word made of A-Z characters, any letter case

    &lt;[A-z]@&gt;

    This matches any single word that contains A-z letters.
    The < character indicate the beginning, while > the end of a word. The [A-z] brackets indicate a series of characters, using the hyphen allows you specify the whole range of A-z letters. Lastly the @ character indicates that the previous expression may repeat 0 to any number of times.

    Match an email from the .com domain

    <[A-z,0-9]@@[A-z,0-9]@.com>

    This matches only emails with A-z letters and 0-9 numbers in their login and domain name. Again the [A-z,0-9] bracket specifies we are listing several ranges of acceptable characters, following this with the @ characters tells that any number of these characters may appear. To use the @ character explicitly we need to escape it with a backslash . We use the similar patter for the domain name. Finally notice again I am using < and > to indicate the beginning or end of a word as emails are not separated by spaces.

    Match a phone number split with hyphens

    [0-9]@-[0-9]@-[0-9]@

    The above matches any 3 series of digits separated by hyphens.

    Using Wildcards to Capture and Replace text

    In some cases you will want to not only capture a pattern but replace it with part of its content. For this you need to use Expressions (). Expressions let you mark a specific group in the “Find what” text field, that you want to reuse in your “Replace with” text field. Below a simple example:

    Example: Switch places of 2 numbers

    In this example we have a pattern of numbers separated by hyphens. Let us assume we want to switch places of these two 3-digit numbers.
    Text:

    Some text 123-456, some other text 789-012.
    Something else 345-678

    Find what:

    ([0-9]{3})-([0-9]{3})

    Replace with:

    -

    The resulting Text:

    Some text 456-123, some other text 012-789.
    Something else 678-345

    Example: Replace Email domain

    Imagine you want to replace an email domain from yahoo to gmail on all emails in your Word document. If you didn’t know Expressions you would use wildcards to find a match an manually replace all such cases. However below an example that will replace this automatically:

    All Expressions () are numbered by the sequence in which they are used. This allows us to reference the first part of the email by using the backslash and number 1.

    VBA Find and Replace

    You can also execute a Find and Replace sequence using a VBA Macro:

    Find a single match

    The below procedure will print out all occurances of “Find Me” phrases.

    ActiveDocument.Content.Select
    With Selection.Find
        .Text = "Find Me"
        .Forward = True
        .Execute
    End With
     
    If Selection.Find.Found Then
          Debug.Print "Found: " & Selection.Range 'Print the found match 
    Else
          Debug.Print "Not Found"
    End If
    

    Find all matches

    Below VBA macro will find all emails in a Word document with their mailto hyperlinks. This is a good example of fixing hyperlinks in Word documents.

    ActiveDocument.Content.Select
    Do
      With Selection.Find
          .Text = "<[A-z,0-9]@@[A-z,0-9]@.com>"
          .MatchWildcards = True
          .Forward = True
          .Execute
      End With
     
      If Selection.Find.Found Then
          ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="mailto:" & Selection.Range
      Else
          Exit Do 'If not found then end the loop
      End If
    Loop
    

    Conclusions

    Here are my main takeaways from using Find and Replace in Microsoft Word

Details
Written by Tibor Környei

Using MS Words Advanced Find and Replace Function

Probably few people are familiar with, and even fewer use, the advanced feature of Microsoft Word’s Find and Replace function. However, this feature may often prove to be extremely helpful in the translator’s work. It can be accessed from the Find and Replace dialog box and it is called, depending on the version of Word, Use pattern matching orUse wildcards. The advanced feature only works after you have checked this option. If it is not presented to you in the dialog box, click the More button.

«Much time can be saved in translating legal, financial, and technical texts by using properly written find-and-replace formulas.»

This feature allows you to set complex search conditions by using special character combinations. The symbols to be used are listed in detail under Word’s Help menu, so we shall not describe them here. The use of this feature will be shown below using a few examples. You may want to test these examples in Word using a test file. 

By highlighting portions of the text, the search can be limited to that portion of the document. Word will perform the search in this portion and then will ask you whether you wish to continue to search in the rest of the text. Click the No button. Replacement can also be performed in the interactive mode by first pressing the Find button and, upon reaching the desired string, deciding whether replacement is required. If so, you press the Replace button; if not, press Find Next.

1. Eliminating extra spaces 

In our work we often accidentally type two or more spaces between words. You can easily replace multiple spaces with a single space using the advanced Find and Replace feature. 

After selecting the Use wildcards option, type the following in the appropriate boxes:

Find what: •{2,}
Replace with:

The • symbol here stands for a regular space. 

The {n,} notation indicates the occurrence of the character or string preceding it at least n times; in this case it indicates that we are looking for a string consisting of at least two spaces. The generic format of the expression is {n,m}, indicating the occurrence of the character preceding it between n and m times. In some non-English versions of the software, asemicolon is used instead of the comma. By clicking Special, you can check which separator character appears in the bracketed expression indicating the number of occurrences.

2. Changing the separator character in numerals 

Numbers written in English in the format 12,345,678.12 are written in some languages in the format 12 345 678,12 (the thousands separator here is not a simple space, but a non-breaking space typed with the key combination Ctrl+Shift+space). In a document with lots of numbers, replacing the separator character manually may be a time-consuming exercise. Use the following:

Find what: ([0-9]),([0-9])
Replace with: 1^s2

The expression in square brackets [0-9] stands for an arbitrary numerical character (digit). By placing an expression between parentheses, it can be referred to as a unit in theReplace with box. The units are numbered from left to right starting with 1. There are two such units in our example. 

The expression in the Find what box means: look for any string of characters where there is one comma between any two digits. 

The expression in the Replace with box means: retype the string found by inserting a non-breaking space between the digits while leaving the digits and their order unchanged. This is indicated by 1 and 2. The caret (^) with the letter s following it is the symbol of a non-breaking space. It can also be inserted by clicking Special and then Nonbreaking space. The same non-breaking space can also be inserted by typing a caret followed by the character’s ANSI code, in this case 0160. This method allows any character to be inserted as long as its ANSI code is known. In this case the replace expression would look as follows:

Find what: ([0-9]),([0-9])
Replace with: 1^01602

In the next step, we shall replace the decimal point with a decimal comma.

Find what: ([0-9]).([0-9])
Replace with: 1,2

The procedure is similar to the one described above; no explanation is needed. 

The reverse procedure when translating into English is somewhat different: 

First we change the decimal comma into a decimal point:

Find what: ([0-9]),([0-9])
Replace with: 1.2

Then we change the non-breaking space into a comma:

Find what: ([0-9])^s([0-9])
Replace with: 1,2

If we wish to process not only non-breaking spaces but also regular spaces functioning as thousands separators (after all, we cannot assume that the author of the original text follows proper word processing practices), we must use the [•^s] (open square bracket — space — caret — letter s — close square bracket) as follows:

Find what: ([0-9])[•^s]([0-9])
Replace with: 1,2


3. Reversing ordinal plus noun 

Hungarian expressions like «2. fejezet», «2. fejezetben» or «2. Fejezet» are all translated into English as «Chapter 2». The find-and-replace operation is the following:

Find what: ([0-9]{1,}).?([Ff]ejeze[a-z]{1,})
Replace with: Chapter^s1

The first {1,} refers to any digit preceding it; the second one refers to an alpha character, indicating that we are looking for one or several such characters. In this way, we can search for numbers consisting of several digits and for flexed forms of words. (Leave out the last letter of the unflexed word stem.) The ? always stands for an arbitrary character; in this way it does not matter whether there is a regular space or a non-breaking space in a given position. Of course, the proper way of looking for both types of space is the use of the [•^s] expression (open square bracket — space — caret — letter s — close square bracket). 

The Find what box means: look for any string of characters where an Arabic number of any length is followed by a period and then, after an arbitrary character (which could also be a non-breaking space), and by a flexed or unflexed form of the word «fejezet» or «Fejezet». The method allows for searching for both upper-case and lower-case forms. 

In the Replace with expression, the number of the chapter will appear instead of 1. 

The method can also be used, with a slight modification, for chapters identified by Roman numerals. For example, «II. fejezet», is to be translated as «Chapter II». The solution:

Find what: ([A-Z]{1,}).?([Ff]ejeze[a-z]{1,})
Replace with: Chapter^s1

All we had to do in order to search for Roman numerals is replace the expression ([0-9]{1,}) with ([A-Z]{1,}). 

In legal texts, an expression of the type «45. §» must often be replaced by an expression of the type «Section 45». This can be easily accomplished on the basis of the above explanations:

Find what: ([0-9]{1,}).[•^s]§
Replace with: Section^s1

The expression [•^s] provides for the possibility of two types of space. The § character could also be written using its ANSI code:

Find what: ([0-9]{1,}).[•^s]^0167
Replace with: Section^s1

Replacement in the reverse direction is also easy. In order to replace an expression of the type «Section 45» with one of the type «45. §», we can proceed as follows:

Find what: Section[•^s]([0-9]{1,})
Replace with: 1.^s§


4. Reversing currency symbols 

Numbers occurring in the format $50,12 must be converted to the format 50,12 $ in the translation. Fortunately, this mechanical task can also be automated. The numbers following the dollar sign can be modified so that the $ sign will immediately follow the number after a non-breaking space.

Find what: $([0-9.,]{1,})
Replace with: 1^s$

The expression can be easily modified so that the word «dollar» (or its plural in the respective language) will appear after the replacement instead of the $ sign.

Find what: $([0-9.,]{1,})
Replace with: 1^sdollar

The Find what box means: look for any expression where a string consisting of numbers, periods and commas immediately follows the $ sign. The disadvantage of this method is that any phrase or sentence ending on «$,» or «$.» will also be converted. We must check before using the replace function whether there is such an expression in the text to be searched. If so, the «$,» and «$.» expressions to be left unchanged must first be replaced by any unique expression (e.g., $comma and $dot) using the regular find-and-replace function and they must be changed back after the replace operation. This artifice can be used in general whenever the harmful side effect of an otherwise useful replace operation is to be avoided. 

The reverse case, when the currency symbol is to be moved from a position after the number to before the number is not as simple and can only be accomplished in several steps. 

In a first step, the thousands separator spaces are replaced with non-breaking spaces (otherwise the $ sign would always appear before the last thousands group):

Find what: ([0-9]) ([0-9])
Replace with: 1^s2

In a second step, the space after the number is replaced, for example, with $$ and «attached» to the number:

Find what: ([0-9])[•^s]$
Replace with: 1$$

Now the currency symbol can be moved to precede the number:

Find what: ([0-9.,^s]{1,})$$
Replace with: $1


5. Handling complex expressions 

When replacing complex expressions, it is convenient to first break down the expression into its components, test the replacement of the components, and then work out a replace formula for the entire expression. 

Let us take the example of the Hungarian expression «10. § (1) bekezdésének d)-f) pontja» into English, which may be «Paragraphs d)-f) of Subsection (1) of Section 10». In this case, the order of the individual expressions is also modified. 

«10. §» would be no problem on the basis of the explanations under point 3. So let us see the replacement of «(1) bekezdésének». We must do the following:

Find what: (([0-9]{1,})) bekezdé[a-z]{1,}
Replace with: Subsection 1

The novelty here is the use of the  «(»  and   «)»  combinations. The parenthesis with a backslash before it distinguishes it as an ordinary character from the same character functioning as an operator. Since the second opening and first closing parentheses are parts of the expression we are searching for (ordinary characters, in contrast to the first opening and second closing parentheses, which function as operators), we must type them as  «(»  and   «)»  in the Find what box. 

Let us examine the part «d)-f) pontja». The solution is the following:

Find what: ([a-z]{1,})?[a-z]{1,}))?pon[a-z]{1,}
Replace with: Paragraphs 1

We used the familiar operators here. By replacing the hyphen and the space with the ? sign, we can make the replace operation handle a hyphen, an n-dash, or a non-breaking space properly. 

Finally, by assembling the components of the entire expression, we obtain:

Find what: ([0-9]{1,}).?§ (([0-9]{1,})) bekezdé[a-z]{1,} ([a-z]{1,})?[a-z]{1,}))?pon[a-z]{1,}
Replace with: Paragraphs 3 of Subsection 2 of Section 1

It is worth noting how easily the reversal of the order in which the individual segments will appear is handled using 3, 2, etc.

Additional options 

The find-and-replace function can also be applied in many other cases, for example, in replacing date formats. It is worth learning how to record and write macros in Word, because even complex tasks can be performed by combining find-and-replace and macros. 

Often the solution of a problem requires some ingenuity. The specific replace formula must always be tested on a test file before using it in an actual translation. The test file can be produced by copying and pasting a portion of the actual text into a new document via the clipboard. 

Attention must be paid to typing the expressions accurately, since a single extra character may make the replace formula unusable. For this same reason, it is recommended that tested and proven replace formulas be saved for future use. They can also be recorded as macros, in which case they can be reused at any time, rather than reinvented over and over again. 

Much time can be saved in translating legal, financial, and technical texts by using properly written find-and-replace formulas. The time and effort spent familiarizing yourself with the advanced find-and-replace feature of Word may yield rich dividends in increased productivity.

The Find and Replace function in Microsoft’s popular word processing program is used to find a particular character string in a text and replace it with another one. As well as visible characters such as numbers, letters and special characters, the function also recognizes control characters. With Find and Replace in Word you can replace tabs, paragraph marks and spaces with other characters with ease, or even delete them altogether. The Find and Replace function in Word is not just useful and practical for text creators and authors. The function can also be used to conveniently edit program scripts or HTML/XML texts. Used correctly, it can help to make your work significantly more efficient.

Contents

  1. Find and Replace in Word: Avoiding errors
  2. Word: Find and Replace – Step by step

Find and Replace in Word: Avoiding errors

The function is particularly efficient if an existing text only has to be changed slightly. But what many people fail to consider is that as easy and convenient as the function appears at first glance, it also has plenty of stumbling blocks to avoid. Therefore, it is important to know what the result will look like before you use the function. Let’s imagine you want to edit the recurring phrase “Press button A and B” in a text.

If you want to replace the word “and” with the word “or”, it is crucial that you copy the spaces before and after the word “and”. Otherwise, chaos is inevitable. Wherever Word finds the character string “and”, it will blindly replace it with “or”. This will turn “hand” into “hor”, “command” into “commor” and “understand” into “understor”. The problem is that you might not immediately notice these changes. It’s highly likely that the spell checker will mark up all of these nonsense words for you. But that isn’t a foolproof method.

The Find and Replace function does make all the requested replacements throughout the text and takes absolutely no account of possible distortions made to your text.

If you have established that your Find and Replace feature in Word is not working as you want it to, you can easily undo the last action performed. Word’s Undo function reverses everything in an instant.

Tip

Microsoft Office 365 which includes automatic updates for greater security and new functions is available from IONOS.

Word with Microsoft 365 and IONOS!

Easily go from pen and paper to digital inking with Word — included in all Microsoft 365 packages!

Office Online

OneDrive with 1TB

24/7 support

Word: Find and Replace – Step by step

  • Step 1: Highlight the section of text you want to find and replace, and then copy your selection.
  • Step 2: Use the shortcut Ctrl + H. The “Find and Replace” window appears. You can also access the function from the navigation pane or the Home ribbon.
  • Step 3: Paste the previously copied text into the first input box (“Find what”).
  • Step 4: In the lower text box (“Replace with”), enter the text you intend to replace it with.
  • Step 5: If you click on “Replace” the function only replaces the character string where you previously highlighted the text. If you click on “Replace all”, Word replaces the character string in the entire document.
“Find and Replace” in Word
With “Find and Replace”, Microsoft Word provides a number of different ways to make your work easier.

The “Find and Replace” function in Word is indifferent to the kind of characters you want to replace. You can replace anything with anything. However, certain character strings represent particular functions. For example, if you want to remove unnecessary paragraph marks, you can also do this using the Find and Replace function. To do this, go into the input screen for the function as normal and open up the advanced search options by selecting “More”. If you select “Special” and then the “Paragraph mark” option, Word automatically enters “^p” in the search box.

If you repeat this (i.e. enter two paragraph marks consecutively) in the “Find what” box and enter a single paragraph mark in the “Replace with” box, you can then confirm with “Replace All” to automatically replace all double paragraph marks in the text with a single paragraph mark. This function is often used when copying texts from other formats – for example websites or PDF documents – into a Word document.

If you want to replace capital letterswith lower case letters, select “More” and check the “Match case” box.

Find and Replace in Word is a very powerful tool. However, we recommend practicing a little so that the function provides you with the desired result.

Related articles

How to save as PDF

Word documents: how to save as a PDF file

If you want to send a Word document or prepare it for printing, it’s recommended you know how to save it as a PDF file. This way, you can be sure that the formatting of your document won’t change and that others will not be able to edit it without permission. For simple conversion tasks, the save function in Word is often sufficient. However, there are some dedicated tools which offer a wider…

Word documents: how to save as a PDF file

Create a table of contents in Word

How to create a table of contents in Word

Microsoft Word makes it easy to create smart text documents with its diverse template styles. This includes pre-formatted table of contents templates. With our illustrated, step-by-step guide, we’ll show you how to find the templates and how to customize the design.

How to create a table of contents in Word

Word Hyphenation

Activate and adjust hyphenation in Word

Hyphenation in Word is a handy tool that is often used to create a more legible document. This feature avoids excessive line breaks and large spaces that sometimes occur in Word documents. We’ll show you how to activate and customize automatic hyphenation in Word.

Activate and adjust hyphenation in Word

How to delete a page in Word

How to delete a blank page in Word

Word sometimes has weird quirks: suddenly a blank page appears in the middle of the document for no reason and cannot be removed. You can quickly reach your (stress) limits in this kind of situation, at least when trying conventional means. But you can delete a page in Word easily, if you know how. The problem usually lies in invisible control characters.

How to delete a blank page in Word

Excel: Find and replace

Excel: Find and Replace – made simple

Microsoft’s favorite spreadsheet software offers a plethora of useful features and tools. Among the most important commands are “Find” and “Replace.” We’ll show you how they work step-by-step. In addition, this article offers tips and tricks to search for unknown values using placeholders.

Excel: Find and Replace – made simple

Понравилась статья? Поделить с друзьями:
  • Replace with enter excel
  • Replace link with word
  • Replace values in excel formulas
  • Replace in word with tab
  • Replace the words in italics in each sentence with a word from the box