Kaip naudoti „RegEx“ programoje „Microsoft Word“ - „Excel“ patarimai

Lissa klausia:

Ar yra būdas pakeisti skaičių (visada atsitiktinį skaičių) po žodžio lapė? Pavyzdys: lapė 23, lokys 1, lapė 398, varlė 12, lapė 15. Noriu pakeisti skaičių į tą pačią žodžio lapė spalvą.

„Microsoft Word“ galime rasti ir pakeisti pagal formatą. Tai puiki savybė greitai surasti suformatuotą tekstą ir netgi pakeisti visą teksto formatą dokumente.

Juostelėje pasirinkite Išplėstinė paieška.

Rasti ir pakeisti dialogą

Įveskite tekstą, kurį norite rasti, tada spustelėkite Daugiau, kad pamatytumėte išplėstines parinktis, ir spustelėkite mygtuką Formatuoti.

Išplėstinės radimo parinktys

Nustatymuose pasirinkite parinktį Šriftas, tada galite nustatyti teksto spalvą, kurią norėtumėte rasti dokumente. Spustelėkite Gerai, kad uždarytumėte dialogo langą Rasti šriftą.

Dialogo lange Rasti šriftą pasirinkite teksto spalvą.

Spustelėkite Rasti kitą ir pamatysite, kad bus pasirinktas pirmasis teksto, kurio ieškoma tam tikra spalva, atsiradimas.

Raskite „Kitas“, kad surastumėte pirmą kartą.

Taip pat galime atlikti sudėtingesnes paieškas naudodami pakaitos simbolius. Tačiau „Word“ savosios paieškos modulis neleidžia mums ieškoti, kaip paprašė Lissa.

Štai kur mes galime pakviesti „RegEx“ į žaidimą!

„VBSCript“ reguliariųjų reiškinių biblioteka

VBA neteikia jokios reguliariosios išraiškos palaikymo. Tačiau „Microsoft VBScript“ bibliotekoje yra galingos reguliaraus reiškimo galimybės. Ši biblioteka yra „Internet Explorer 5.5“ ir naujesnių versijų dalis, todėl ją galima naudoti visuose kompiuteriuose, kuriuose veikia „Windows XP“, „Vista“, 7, 8, 8.1 arba 10.

„Mac“ vartotojai

Kadangi „Internet Explorer“ nėra „Mac“ programa, šios bibliotekos „Mac“ nėra. Todėl toliau pateikti VBA pavyzdžiai neveikia „Mac“.

Norėdami naudoti šią biblioteką VBA, perjunkite į VBE, VBE meniu pasirinkite Projektas ir nuorodos, tada slinkite žemyn sąraše, norėdami rasti elementą „Microsoft VBScript Regular Expressions 5.5“, ir pažymėkite jį, kad įtrauktumėte į programą.

„VBScript“ reguliariųjų reiškinių biblioteka

Įdėkite naują modulį ir nukopijuokite bei įklijuokite šį kodą į šį modulį.

Sub doRegexFind() Dim strSample As String Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match strSample = "First product code is fox 12, second one is fox 22, and third product is fox 45." Set objRegex = New RegExp With objRegex .Pattern = "fox d+" .Global = True .IgnoreCase = True Set matches = .Execute(strSample) For Each fnd In matches Debug.Print fnd Next fnd End With End Sub

Ši procedūra paima teksto pavyzdį, suranda produkto kodus pagal pateiktą šabloną, kuris prasideda „lape“, vienu tarpu ir skaičiumi, ir išspausdina suderintus kodus iškarto lange (paspauskite Ctrl + G VBE, jei jis nėra jau matoma).

Atitinkantys produktų kodai, atspausdinti lange Nedelsiant.

d+ Rašto simbolių klasė apibrėžia vieną ar daugiau skaitinių simbolių, o šablonas iš esmės yra „lapės“ priešdėlis, po kurio yra tarpas, po kurio eina skaičiai.

Daugiau informacijos

Jei norite gauti daugiau informacijos apie simbolių ištrūkimus, simbolių klases ir inkarus, apsilankykite „Regular Expression Language - Quick Reference“.

Nukopijuokite ir įklijuokite šį kodą, kad pamatytumėte veiksmą „RegEx“, kad pašalintumėte tarpus tarp produktų kodų.

Sub doRegexFindReplace() Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match Dim strSample As String strSample = "First product code is fox 12, second one is fox 22, and third product is fox 45." Set objRegex = New RegExp With objRegex .Pattern = "(fox) (d+)" .Global = True .IgnoreCase = True strSample = .Replace(strSample, "$1$2") End With Debug.Print strSample End Sub

Ši procedūra pakeičia teksto turinio pavyzdį, pašalindama tarpus iš gaminio kodų, suderintų su pateiktu šablonu, ir išspausdina rezultato tekstą lange Nedelsiant.

Pakeistas tekstas, atspausdintas lange Nedelsiant.

Atminkite, kad modelis šiek tiek skiriasi nuo pirmojo kodo. Šio modelio terminai pridedami prie skliaustų, o atitinkami terminai pakeisti metodu naudojami kaip $ 1 ir $ 2 eilės tvarka. Ši procedūra tiesiog sujungia du terminus be tarpų.

Grįžti prie klausimo

Grįžkime prie pavyzdinio teksto, kurį naudojome šio straipsnio pradžioje.

Teksto pavyzdys

Turime rasti „lapę“, po kurios eina skaitiniai simboliai, ir pakeisti atitikimą, naudojant suderinto teksto skilties „lapė“ spalvą.

Although RegEx is very good matching by the given pattern, it cannot replace the color of text in Word document. So we will combine RegEx and Word VBA methods in the following procedure.

Here are the steps:

  1. Find the matches with RegEx.
  2. Search each matched text by using Word Find method.
  3. Find the color of the first word in the found range.
  4. Change the color of the found range with the color in the previous step.

Switch to VBE, and insert a new module. Make sure VBScript Regular Expressions library is added to the project, and copy and paste the following code into this new module.

Sub doRegexMagic() Dim str As String Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match Set objRegex = New RegExp str = "fox" With Selection .HomeKey wdStory .WholeStory End With With objRegex .Pattern = str & " d+" .Global = True .IgnoreCase = True Set matches = .Execute(Selection.Text) End With With Selection .HomeKey wdStory With .Find .ClearFormatting .Forward = True .Format = False .MatchCase = True For Each fnd In matches .Text = fnd .Execute With Selection .Font.Fill.ForeColor = .Range.Words(1).Font.TextColor .MoveRight wdCharacter End With Next fnd End With .HomeKey wdStory End With End Sub 

Run the code, and here is the result.

Result

Download Word File

To download the Word file: how-to-use-regex-in-microsoft-word.docm

RegEx in Excel?

Regex is completely missing from Excel. However, we can still use VBScript Regular Expressions in Excel VBA.

Launch Excel, open a new workbook, and create the content as shown below.

Sample data in Excel

Reference

This article has been inspired by Learn Excel 2010 - "Find & Replace Color of A Certain Word": Podcast #1714 published by Bill Jelen on May 21, 2013! So we wanted to use similar sample text as he used in the video. We just added numbers after the "fox".

Switch to VBE, and insert a new module. Make sure VBScript Regular Expressions library is added to the project just like you did in Word, and copy and paste the following code into this new module.

Sub doRegexMagicInExcel() Dim str As String Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match Dim rng As Range Dim cll As Range Set objRegex = New RegExp Set rng = Selection str = "fox" With objRegex .Pattern = "(" & str & ") (d+)" .Global = True .IgnoreCase = True For Each cll In rng.Cells Set matches = .Execute(cll.Value) For Each fnd In matches cll.Value = .Replace(cll.Value, "$1$2") Next fnd Next cll End With End Sub

Return to worksheet, and select the range with sample text. Run the macro, and see the result.

Result in Excel

This procedure loops through the cells in the selected range, replaces the text in the cells by removing the spaces from the product codes matched with the given RegEx pattern.

Download Excel File

To download the Excel file: how-to-use-regex-in-microsoft-excel.xlsm

Įdomios straipsniai...