Match case in word

Use the word processor’s search function to locate text and more

Updated on December 15, 2020

What to Know

  • Basic word search: Go to the Home tab. Select Find and enter the text for the search.
  • Advanced search: Go to Home > Find. Choose the search drop-down arrow. Select Options and select your criteria.

This article explains how to search for text in Microsoft Word. The information applies to Word 2019, Word 2016, Word 2013, Word 2010, Word Online, and Word for Microsoft 365.

How to Do a Basic Word Search in MS Word

Microsoft Word includes a search function that makes it easy to search for different elements in a document, including text. Use the basic tool to look for instances of a specific word, or the advanced options to perform tasks such as replace all instances of a word with another one or search for equations.

To run a basic search for a specific word or phrase in Word:

  1. Go to the Home tab and select Find, or press Ctrl+F.

    In older versions of Microsoft Word, select File > File Search.

  2. In the Navigation pane, enter the text you want to search for. A list of matching words displays in the Navigation pane and instances of the word are highlighted in the main document.

  3. Cycle through the results in the Navigation pane in one of three ways:

    • Press Enter to move to the next result.
    • Select a result with the mouse.
    • Select the Up and Down arrows to move to the previous or next result.
  4. Make any changes or edits to the document as needed.

  5. Select the Down arrow to move to the next instance of the word.

Match Case, Whole Words Only, and More

Beyond searching for every instance of a word, you can get more specific about what you want to find. For example, to find whole instances of a word and not every word that contains the letter combination or to find instances of a word that aren’t capitalized.

Here’s how to do an advanced search:

  1. Select Home > Find.

  2. In the Navigation pane, select the Search drop-down arrow.

  3. Choose Options.

  4. In the Find Options dialog box, choose the description that best fits what you’re trying to find. For example, to find instances of a word with the same capitalization, select Match case.

  5. Select OK.

Use Advanced Find

Many of the choices available in the Find Options dialog box are also available in Advanced Find. Advanced Find includes the option to replace the text with something new. Based on your selection, Word replaces one instance or all instances at once. You can also replace the formatting, or change the language, paragraph, and tab settings.

Find Instances of Other Elements

Other options in the Navigation pane include searching for equations, tables, graphics, footnotes, endnotes, and comments.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

Find and Replace Text and Numbers in Word

by Avantix Learning Team | Updated March 7, 2022

Applies to: Microsoft® Word® 2013, 2016, 2019, 2021 or 365 (Windows)

You can find and replace in Word using the Find and Replace dialog box as well as the Navigation Pane. If you use the dialog box, you can find and replace text and numbers and use wildcards for more advanced find and replace tasks. Wildcards are useful when you are not able to find an exact match. You can display the Find and Replace dialog box using a keyboard shortcut or the Home tab in the Ribbon.

Recommended article: How to Quickly Remove Hard Returns in Word Documents

Do you want to learn more about Microsoft Word? Check out our virtual classroom or in-person Word courses >

Note: Screenshots in this article are from Word 365 but are similar in previous versions of Word.

The Replace command appears on the Home tab in the Ribbon in the Editing group:

Replace command on Home tab in the Ribbon to find and replace words or characters.

Using the Find and Replace dialog box to replace words or characters (and match case)

You can perform simple find and replace tasks using the Replace dialog box in its collapsed state. To access more advanced options, you will need to click More in the Replace dialog box to expand it.

To use the Find and Replace dialog box to find and replace text in Word (words or characters) and match case if needed:

  1. Click the Home tab in the Ribbon.
  2. In the Editing group, click Replace to display the Replace dialog box. Alternatively, press Ctrl + H if you prefer to use a keyboard shortcut to open the Replace dialog box.
  3. Enter the text you want to find in the Find What box. You can specify whether Word should locate only matches with the exact capitalization by clicking More and then selecting or checking Match case.
  4. Enter the text you want to replace in the Replace box.
  5. Click Find Next and then click Replace for each occurrence or click Replace All.
  6. Click Close.

In the following example, the Replace dialog box has been expanded to display other options including Match case:

Replace dialog box in Word to find and replace using exanded options.

Finding and replacing using wildcards

To use wildcards, you will need to use the Find and Replace dialog box and expand it to display more options. You can then select the option to Use wildcards. A wildcard can replace one or more characters in a string of text or numbers. The most common wildcard is the asterisk (*).

It’s important to note that wildcard searches are case sensitive. Also, Word uses «lazy» pattern matching so it will stop matching as soon as possible. This means that you could enter part of a word and find that part without using wildcards.

To find and replace text using wildcards in Word:

  1. Position the cursor at the location in the document where you want to start finding and replacing. If you want to start at the beginning of the document, you can press Ctrl + Home.
  2. Click the Home tab in the Ribbon.
  3. In the Editing group, click Replace. Alternatively, press Ctrl + H. A dialog box appears.
  4. Select More to expand the dialog box.
  5. Click in the Find What box.
  6. Select or check the Use wildcards checkbox.
  7. Enter the text and wildcard(s) you want to use. For example, enter s*l to find any text starting with s and ending with l.
  8. Click in the Replace with box.
  9. Enter the text you want to use to replace the text in the Find what box.
  10. Click Find Next to find the first instance of the characters you want to find.
  11. Click Replace or Replace All. If you click Replace, Word will select the next matching characters in the Find what box. If you click Replace All, Word will display a dialog box with the number of replacements. In this case, click OK.
  12. If necessary, click Replace again. Repeat for each instance.
  13. Click Close to close the dialog box.

In the following example, b*s has been entered in the Find what box to find any word starting with starting with b and ending with s:

Find and replace in Word using the Replace dialog box and wildcards.

If you want to undo a Replace or Replace All action, close the dialog box and press Ctrl + Z.

Using common wildcards

The most common wildcards you can use in the Find and Replace dialog box are the asterisk (*) to find multiple characters and the question mark (?) to find a single character.

For example:

b*l will find ball and barrel (a character followed any characters and ending with a specific character)

h?ll will find hill and hall (a character followed by any single character and then followed by 2 characters)

Using wildcards to find one or more instances of the same character

You can also use @ as a wildcard to find one or more instances of the same character.

For example:

catchal@ will find catchal or catchall

Using wildcards for alternate characters and ranges

You can also use wildcards to find alternate characters or ranges of characters. These are entered in square brackets [ ] and may be combined with other wildcards.

[ ] can be used to find each of a set of characters

[ – ] can be used to find each of a set of characters in a range

You can use any character or series of characters in a range within the square brackets (including the space character). Characters are processed in alphanumeric order from lowest to highest.

For example:

[abc] will find any of the letters a, b, or c

[G] will find the upper case letter G

[A-Z] will find any upper case letter

[0-9] will find any single number

[13579] will find any odd number

[0-9A-z] will find any number or letter

f[ai]n will find each of the characters in square brackets such as fan or fin

[b-f]at will find each of a range of characters such as bat, cat, and fat

Using wildcards to omit characters

If you want to omit specific characters, you can use an exclamation mark (!) combined with square brackets.

For example:

[!f]ast will find last and past but not fast

Using wildcards to find the beginning or end of a word

You can use the less than symbol (<) to find the beginning of a word and the greater than symbol (>) to find the end of a word. These wildcards are combined with characters in round brackets or parentheses.

For example,

<(watch) will find watching or watchman

(all)> will find wall or stall

These wildcards can be problematic if you are using a wildcard and you want to find > or < as characters in the document. If this is the case, enter a backslash () in front of the character so that it is not treated as a wildcard.

For example,

<*> will find <h1> or <h2>

Using wildcards to find instances of a character

You can use curly brackets { } to specify the number of instances of a character. These brackets can be combined with a comma to specify the number of instances. Counting can be used with individual characters or with sets of characters.

{n} is used to find the number of instances of a character

{n,} is used to find at least n instances of a character

{n,m} is used to find between n and m instances of a character

For example:

^p{2} will find two consecutive paragraph marks or hard returns (^p is a special character for a paragraph mark in Word)

{3} will find three spaces (there is a space entered before the first curly bracket)

30{2,} will find at least 2 instances of the preceding character such as 3000 or 30000

30{3,4} will find between 3 and 4 instances of the preceding character such as 30000 or 300000 not 300

These last wildcards are particularly useful if you are finding and replacing numbers in Word.

The Find and Replace dialog box offers more functionality as well. For example, you can also Find and Replace Formatting in Word.

Subscribe to get more articles like this one

Did you find this article helpful? If you would like to receive new articles, join our email list.

More resources

How to Add Page Numbers in Word (Step by Step)

How to View Document Statistics in Microsoft Word

How to Update All Figure Numbers in Microsoft Word

How to Check Word Count in Microsoft Word (4 Ways)

How to Superscript or Subscript in Word (with Shortcuts)

Related courses

Microsoft Word: Intermediate / Advanced

Microsoft Word: Designing Dynamic Word Documents Using Fields

Microsoft Word: Long Documents Master Class

Microsoft Word: Accessible Word Documents

Microsoft Excel: Intermediate / Advanced

Microsoft PowerPoint: Intermediate / Advanced

VIEW MORE COURSES >

Our instructor-led courses are delivered in virtual classroom format or at our downtown Toronto location at 18 King Street East, Suite 1400, Toronto, Ontario, Canada (some in-person classroom courses may also be delivered at an alternate downtown Toronto location). Contact us at info@avantixlearning.ca if you’d like to arrange custom instructor-led virtual classroom or onsite training on a date that’s convenient for you.

Copyright 2023 Avantix® Learning

Microsoft, the Microsoft logo, Microsoft Office and related Microsoft applications and logos are registered trademarks of Microsoft Corporation in Canada, US and other countries. All other trademarks are the property of the registered owners.

Avantix Learning |18 King Street East, Suite 1400, Toronto, Ontario, Canada M5C 1C4 | Contact us at info@avantixlearning.ca

Начиная с версии 3.10 в языке Python наконец-то появилась конструкция switch-case, которая называется match-case.

С помощью выражения match-case можно избавиться от довольно громоздких цепочек if-elif-else, например:

http_status = 400
if http_status == 400:
    print("Bad Request")
elif http_status == 403:
    print("Forbidden")
elif http_status == 404:
    print("Not Found")
else:
    print("Other")

Вместо этого можно использовать компактное выражение match-case:

http_status = 400
match http_status:
    case 400:
        print("Bad Request")
    case 403:
        print("Forbidden")
    case 404:
        print("Not Found")
    case _:
        print("Other")

Во многих случаях последний вариант гораздо лучше. Он делает код более читаемым и менее повторяемым.

В данной статье мы полностью опишем конструкцию match-case в Python. Также мы рассмотрим распространенные проблемы с операторами if-else и варианты их решения при помощи конструкции match-case. И, наконец, разберем 5 ситуаций, в которых можно использовать операторы match-case.

От редакции Pythonist: вам также может быть интересна статья «Используем словари как альтернативу конструкции if-else».

Итак, приступим к делу!

Проблема операторов if-else

В принципе, операторы if-else не всегда являются наиболее интуитивным способом сравнения, и речь не только о Python. Это особенно верно, когда блоки if-else повторяются и формируют длинные цепочки.

Рассмотрим пример на псевдокоде, где при помощи операторов if-else проверяется день недели:

day = "Monday"
if day == "Sunday" {
    print("Take it easy")
}
else if day == "Monday" {
    print("Go to work")
}
else if day == "Tuesday" {
    print("Work + Hobbies")
}
else if day == "Wednesday" {
    print("Meetings")
}
else if day == "Thursday" {
    print("Presentations")
}
else if day == "Friday" {
    print("Interviews and party")
}
else if day == "Saturday" {
    print("Time to do sports")

Как видите, в этом фрагменте кода много повторений.

Проверка day == "something" повторяется многократно. И совершенно ясно, что при каждой проверке мы обращаемся к переменной day. Если бы можно было не повторять day == "something", код стал бы чище и короче.

Избавиться от подобных повторов позволяет switch-case. Это решение есть в большинстве популярных языков программирования.

Решение проблемы — конструкция switch-case

Конструкция switch-case делает структуру сравнения более плавной.

Используя switch-case, вы указываете интересующее вас значение и задаете шаблоны (case) для каждого возможного результата. Затем код пытается сопоставить значение с шаблонами.

Использование оператора switch-case помогает избежать повторений и делает код чище.

Для примера заменим if-else на switch-case в нашем примере псевдокода :

day = "Monday"
switch day {
  case "Sunday"   : print("Take it easy")
  case "Monday"   : print("Go to work")
  case "Tuesday"  : print("Work + Hobbies")
  case "Wednesday": print("Meetings")
  case "Thursday" : print("Presentations")
  case "Friday"   : print("Interviews and party")
  case "Saturday" : print("Time to do sports")

Это выглядит намного чище и короче, чем куча if-else в примере в предыдущем разделе.

Switch-case часто встречается в популярных языках программирования, например в C++.

Python 3.10 также поддерживает конструкцию switch-case. Но она носит другое название — match-case.

Давайте теперь подробно разберем эти операторы именно в языке Python.

Итак, начиная с версии 3.10 язык Python начинает поддерживать конструкцию switch-case. Напоминаем, что в Python она называется match-case.

Оператор match-case также известен как оператор структурного сопоставления с заданным шаблоном.

Задача, решаемая этим оператором, описана в предыдущем разделе. Короче говоря, он заменяет повторяющиеся операторы if-else компактной структурой сравнения с шаблоном.

match-case в Python

Общая структура match-case в Python имеет следующий синтаксис:

match element:
    case pattern1:
        # statements
    case pattern2:
        # statements
    case pattern3:
        # statements

В этой конструкции кода:

  • match element означает «сопоставьте элемент со следующими шаблонами»
  • затем каждое выражение case pattern сравнивает элемент с указанным шаблоном (это может быть, например, строка или число)
  • если шаблон соответствует элементу, выполняется соответствующий блок кода, после этого оператор match-case заканчивает свою работу.

В общем, все то же самое, что и с применением оператора if-elif-else, но с меньшим количеством повторений.

Пример

Давайте теперь реализуем на Python пример с днями недели, который до этого был написан на псевдокоде. Обычный код с if-else будет выглядеть так:

day = "Monday"

if day == "Sunday":
    print("Take it easy")
elif day == "Monday":
    print("Go to work")
elif day == "Tuesday":
    print("Work + Hobbies")
elif day == "Wednesday":
    print("Meetings")
elif day == "Thursday":
    print("Presentations")
elif day == "Friday":
    print("Interviews and party")
elif day == "Saturday":
    print("Time to do sports")

Этот фрагмент кода работает, но выглядит так себе. С оператором match-case в Python 3.10 можно написать красивее:

day = "Monday"

match day:
    case "Sunday"    : print("Take it easy")
    case "Monday"    : print("Go to work")
    case "Tuesday"   : print("Work + Hobbies")
    case "Wednesday" : print("Meetings")
    case "Thursday"  : print("Presentations")
    case "Friday"    : print("Interviews and party")
    case "Saturday"  : print("Time to do sports")

Не правда ли, смотрится лучше? Как только вы адаптируетесь к чтению такой структуры, данный код будет казаться вам куда читабельнее предыдущего.

Кстати, вы можете разбить выражения case на несколько строк, если это более удобно.

Вот наш код, где каждое выражение находится в отдельной строке:

day = "Monday"

match day:
    case "Sunday":
        print("Take it easy")
    case "Monday":
        print("Go to work")
    case "Tuesday":
        print("Work + Hobbies")
    case "Wednesday":
        print("Meetings")
    case "Thursday":
        print("Presentations")
    case "Friday":
        print("Interviews and party")
    case "Saturday":
        print("Time to do sports")

Теперь у вас есть общее представление о том, как код с выражениями match-case может упростить код с if-else.

Теперь давайте рассмотрим типы шаблонов для сопоставления в выражениях match-case.

5 распространенных типов шаблонов для match-case

В выражениях match-case можно использовать различные типы шаблонов. Наиболее примечательные варианты:

  1. Шаблон литерал (literal).
  2. Шаблон захвата (capture).
  3. Шаблон подстановки (wildcard).
  4. Шаблон постоянных значений (constant value).
  5. Шаблон последовательностей (sequence)

Рассмотрим теперь каждый вариант отдельно.

Шаблон литерал (literal)

Самый простой вариант использования match-case — это сопоставление с литеральными шаблонами. Литерал, с которым можно сравнивать, может быть:

  • числом
  • строкой
  • None
  • True
  • False

Хорошим примером данного шаблона является уже рассмотренный нами код с днями недели. В нем мы сравниваем строковые литералы с переменной day:

day = "Monday"

match day:
    case "Sunday"    : print("Take it easy")
    case "Monday"    : print("Go to work")
    case "Tuesday"   : print("Work + Hobbies")
    case "Wednesday" : print("Meetings")
    case "Thursday"  : print("Presentations")
    case "Friday"    : print("Interviews and party")
    case "Saturday"  : print("Time to do sports")

Этот код проверяет, какое значение имеет переменная day. На основании этого он выполняет действие, которое в данном случае представляет собой простой вывод в консоль.

Шаблон захвата (capture)

Выражение match-case можно использовать для сохранения (захвата) совпавшего значения в переменную.

Лучше всего это продемонстрировать на примере.

Давайте создадим функцию greet(), которая приветствует человека, если указано его имя.

def greet(name=None):
    match name:
        # Check if name == None
        case None:
            print("Hello there")
        # Store name into some_name if it is not None
        case some_name:
            print(f"Hello {some_name}")

greet()       # Prints "Hello there"
greet("Jack") # Prints "Hello Jack"

Выражение match-case делает две вещи (результат указан в комментариях):

  • Проверяет, имеет ли переменная name значение None. Если это так, в консоли отображается приветственное сообщение по умолчанию.
  • Проверяет, имеет ли переменная name какое-либо другое значение. Если да, это имя сохраняется в переменную some_name. И дальше в консоль выводится приветствие именно с этим именем.

Шаблон подстановки (wildcard)

При использовании выражения match-case вы можете применять знак подстановки для сопоставления без привязки к конкретному значению. При этом подстановка соответствует всему, что не включено в выражения case. В некотором смысле подстановка — это блок else выражения match-case.

Для знака подстановки используется символ подчеркивания _.

Первый пример использования знака подстановки

Например, давайте проверять результат бросания монеты:

coinflip = 4
match coinflip:
    case 1:
        print("Heads")
        exit()
    case 0:
        print("Tails")
    case _:
        print("Must be 0 or 1.")

Результат:

Must be 0 or 1.

Здесь знак подстановки соответствует всему кроме 0 или 1. В нашем коде результат подбрасывания монеты в переменной coinflip по какой-то причине равен 4. Этот результат совпадает с подстановкой и поэтому запускается соответствующее действие.

Это один из способов использования шаблона подстановки в выражениях match-case.

Второй пример использования знака подстановки

Допустим, вам безразличны значения элементов некоторой коллекции. Вам просто нужно убедиться, что эти элементы существуют, иными словами важно их количество.

Например, давайте проверим размер кортежа, не рассматривая значения его элементов:

location = (0, 0)
match location:
    case(_,):
        print("1D location found")
    case(_, _):
        print("2D location found")
    case(_, _, _):
        print(("3D location found"))

Результат:

2D location found

Как можно заметить, в этом случае проверяется только количество найденных элементов. Здесь мы использовали подстановку, чтобы убедиться, что в кортеже есть два элемента, не заботясь об отдельных значениях элементов.

То же самое можно сделать, используя оператор if-else и функцию len(). Но если операторы if-else становятся слишком длинными, лучше использовать оператор match-case для повышения качества кода.

Шаблон постоянных значений и перечисления

В качестве шаблонов выражения match-case можно использовать элементы перечислений (enumerations).

Чтобы это продемонстрировать, давайте создадим класс перечисления Direction (унаследованный от класса Enum), представляющий четыре основных направления на компасе.

Далее создадим функцию handle_directions(), которая принимает элемент класса Direction в качестве входного аргумента. Эта функция сопоставляет этот аргумент с одним из направлений из перечисления и реагирует соответствующим образом.

Вот сам код:

from enum import Enum

class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4
def handle_directions(direction):
    match direction:
        case Direction.NORTH: print("Heading North")
        case Direction.EAST: print("Heading East")
        case Direction.SOUTH: print("Heading South")
        case Direction.WEST: print("Heading West")

Теперь можно вызвать функцию handle_directions() следующим образом:

handle_directions(Direction.NORTH)

Конечно, приведенный выше код можно заменить чем-то более коротким или простым. Но этот пример наглядно демонстрирует, как можно использовать перечисления вместе с выражениями match-case.

Шаблон последовательностей

Для сопоставления с заданным шаблоном можно использовать распакованные элементы различных последовательностей (коллекций).

Если вы вдруг не знаете, что такое распаковка, то это означает вытягивание значений последовательности в отдельные переменные.

Вот пример распаковки списка в четыре переменные:

directions = ["North", "East", "South", "West"]

# Grab the values from a list and store them into variables
n, e, s, w = directions
print(n) # prints North
print(e) # prints East
print(s) # prints South
print(w) # prints West

Таким образом, распаковку можно использовать вместе с выражением match-case.

Например, давайте проверим, является ли местоположение (переменная location) точкой 1D, 2D или 3D. Кроме того, давайте будем сохранять значения координат в отдельных переменных в зависимости от количества измерений.

location = (1, 3)

match location:
    case x, :
        print(f"1D location found: ({x})")
    case x, y:
        print(f"2D location found: ({x}, {y})")
    case x, y, z:
        print((f"3D location found: ({x}, {y}, {z})"))

Результат:

2D location found: (1, 3)

Данный код сопоставляет переменную location, в которой сохранен некий кортеж с координатами, с кортежами из одного, двух или трех элементов. А затем значения координат распаковываются в различные переменные.

Если в кортеже больше значений, но важны только первые три, можно использовать оператор *.

Допустим, есть кортеж с координатами, сохраненный в переменную location. И вдобавок в нем еще могут храниться посторонние элементы. Чтобы отловить «лишние» элементы, воспользуемся оператором *:

location = (1, 3, 2, "a", "b", "c")

match location:
    case x, :
        print(f"1D location found: ({x})")
    case x, y:
        print(f"2D location found: ({x}, {y})")
    case x, y, z, *names:
        print((f"3D location found: ({x}, {y}, {z})"))
        print(f"Also, there was some extra data: {names}")

Результат:

3D location found: (1, 3, 2)
Also, there was some extra data: ['a', 'b', 'c']

Теперь выражение *names захватывает все остальные элементы, вне зависимости от того, сколько их там есть.

Теперь вы знаете основные типы шаблонов, с которыми можно производить сравнения. И последнее, но не менее важное: давайте посмотрим, как комбинировать шаблоны в выражении match-case.

Комбинирование шаблонов в match-case

В конструкции match-case можно сравнивать сразу несколько шаблонов.

Для этого используется логический оператор |(или). Таким образом проверяется, соответствует ли хотя бы один шаблон заданному значению.

Например, давайте проверим, выходным или рабочим днем является день недели:

day = "Monday"

match day:
    case "Saturday" | "Sunday":
        print("Weekend")
    case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
        print("Work")

Результат:

Work

Заключение

Во многих языках программирования длинные цепочки операторов if-else можно заменять более аккуратными операторами switch-case.

И наконец-то в версии Python 3.10 была реализована аналогичная функция — match-case.

Перевод статьи Arturri Jalli Python ‘switch case’ Statement: A Complete Guide (match case).

Понравилась статья? Поделить с друзьями:
  • Match any word after
  • Match a word and a definition amazing
  • Match any part of the word
  • Match a verb from a with a word or phrase from b read a magazine
  • Match and vlookup in excel