Search code examples
c#regexwpfregular-language

Writing a regular expression that will select a string


I have a .txt that contains names of cakes (below * Exported from... ) and where is it exported from. I'm doing a UI in WPF/C# and I have a textbox where you can enter a string and click the "search" button. I want to write a regular expresion that will only look for that string in the whole name of the cake and display all the names of cakes with that string. I don't see a pattern with those names.

For example:

Input --> In the textbox I enter: Strawberry

Output --> Strawberry Shortcake , Eva's Strawberry Cake

Here is my .txt file:

                * Exported from MasterCook *

                        Blueberry Crunch Coffee Cake

                * Exported from MasterCook *

                        Filled Berlin Doughnuts (Bismarks)

                * Exported from MasterCook *

                        Strawberry Shortcake

                * Exported from MasterCook *

                         Eva's Strawberry Cake

                * Exported from MasterCook *

                        Fresh Apple Cake #3

                * Exported from MasterCook *

                         Frozen Lady Heath Dessert **

                * Exported from MasterCook *

                        Grandma Stefan's German Cheese Torte

Solution

  • I don't know how big your list of cakes is, but they way you've described the problem doesn't require RegEx at all. RegEx evaluates one line at a time by default--unless you specifically tell it otherwise.

    The regular expression ".*Strawberry.*" is essentially the same as a mystring.Contains("Strawberry"). The Contains() method is much faster than the regex option, which can make a big difference if the list is very large.

    The thing you need to manage is the list of cakes. You can read the file once and store the list of cakes in a list, or if the file is huge you can put it in a database or a Lucene index.