Microsoft Word'de RegEx Nasıl Kullanılır - Excel İpuçları

Lissa soruyor:

Fox kelimesinden sonraki bir sayıyı (her zaman rastgele bir sayı) değiştirmenin bir yolu var mı? Örnek: tilki 23, ayı 1, tilki 398, kurbağa 12, tilki 15. Sayıyı tilki kelimesiyle aynı renkle değiştirmek istiyorum.

Microsoft Word'de biçime göre bulabilir ve değiştirebiliriz. Bu, biçimlendirilmiş metni hızlıca bulmak ve hatta belgedeki tüm metin biçimini değiştirmek için harika bir özelliktir.

Şeritte Gelişmiş Bul'u seçin.

Bul ve Değiştir İletişim Kutusu

Bulunacak metni girin, ardından gelişmiş seçenekleri görmek için Daha Fazla düğmesini tıklayın ve Biçim düğmesini tıklayın.

Gelişmiş Bul Seçenekleri

Ayarlarda Yazı Tipi seçeneğini seçin, ardından belgede bulmak istediğiniz metin rengini ayarlayabilirsiniz. Font Bul iletişim penceresini kapatmak için Tamam'a tıklayın.

Font Bul iletişim kutusunda metin rengini seçin.

Sonrakini Bul'a tıkladığınızda, aranan metnin belirli bir renkte ilk geçtiği yerin seçileceğini göreceksiniz.

İlk geçtiği yeri bulmak için İleri'yi bulun.

Joker karakter kullanarak daha karmaşık aramalar da yapabiliriz. Ancak, Word'ün yerel arama modülü, Lissa'nın sorduğu gibi bir arama yapmamıza izin vermiyor.

Oyuna RegEx diyebileceğimiz yer burası!

VBSCript Normal İfadeler Kitaplığı

VBA, herhangi bir normal ifade desteğiyle birlikte gönderilmez. Ancak Microsoft VBScript kitaplığı güçlü normal ifade yetenekleri içerir. Bu kitaplık, Internet Explorer 5.5 ve sonraki sürümlerinin bir parçasıdır, bu nedenle Windows XP, Vista, 7, 8, 8.1 veya 10 çalıştıran tüm bilgisayarlarda mevcuttur.

Mac Kullanıcıları

Internet Explorer bir Mac uygulaması olmadığından, bu kitaplık Mac'te mevcut değildir. Bu nedenle, aşağıdaki VBA örnekleri Mac'te çalışmaz.

Bu kitaplığı VBA'da kullanmak için, VBE'ye geçin, VBE menüsünde Proje ve Referanslar'ı seçin, ardından "Microsoft VBScript Normal İfadeler 5.5" öğesini bulmak için listeyi aşağı kaydırın ve uygulamaya dahil etmek için işaretleyin.

VBScript Normal İfadeler Kitaplığı

Yeni bir modül ekleyin ve aşağıdaki kodu kopyalayıp bu modüle yapıştırın.

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

Bu prosedür örnek metni alır, verilen modele göre ürün kodlarını bulur - bu "tilki", tek boşluk ve bir sayı ile başlar ve eşleşen kodları Hemen penceresine yazdırır (değilse VBE'de Ctrl + G tuşlarına basın. zaten görünür).

Hemen penceresinde yazdırılan eşleşen ürün kodları.

d+ kalıptaki karakter sınıfı bir veya daha fazla sayısal karakteri tanımlar ve kalıp temelde "tilki" önekinden sonra bir boşluk ve ardından rakamlardan oluşur.

Daha fazla bilgi

Karakter çıkışları, karakter sınıfları ve çapalar hakkında daha fazla bilgi için Normal İfade Dili - Hızlı Başvuru sayfasını ziyaret edin.

Ürün kodlarındaki boşlukları kaldırmak üzere RegEx'in nasıl çalıştığını görmek için aşağıdaki kodu kopyalayıp yapıştırın.

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

Bu prosedür, verilen modelle eşleşen ürün kodlarındaki boşlukları kaldırarak örnek metin içeriğini değiştirir ve sonuç metnini Hemen penceresine yazdırır.

Hemen penceresinde yazdırılan değiştirilmiş metin.

Lütfen desenin ilk koddan biraz farklı olduğunu unutmayın. Bu desendeki terimler parantez içine alınır ve karşılık gelen terimler Değiştir yönteminde sırasıyla 1 $ ve 2 $ olarak kullanılır. Bu prosedür, iki terimi boşluksuz olarak birleştirir.

Soruya Geri Dön

Bu makalenin başında kullandığımız örnek metne geri dönelim.

Örnek yazı

"Fox" ve ardından sayısal karakterler bulmalı ve eşleşen metinde "fox" bölümünün rengini kullanarak eşleşmeyi değiştirmeliyiz.

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

Ilginç makaleler...