[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Help with creating a regex pattern

Posted on 2011-10-17
7
Medium Priority
?
495 Views
Last Modified: 2012-08-13
Hi all,

I am new to RegEx, and it seems very confusing to me. I need to create a regex pattern to loop through a list of strings, and one by one check if the strings match at least one of a list/set of patterns.

I.e. I would for example have a list of patterns:
- Starts with Abc and ends with 123
- Starts with Cde and ends with 234
- Starts with Efg and ends with 345
etc.
(not case-sensitive)

I would have to create a regex expression (built in code, at runtime) that can be used to check each string in a list of strings one at a time to see if it matches pattern 1, pattern 2 or pattern 3 etc

Could anyone please give me a hint (or even better the solution) to this problem?

Peter
0
Comment
Question by:pblsoft
  • 4
  • 3
7 Comments
 

Author Comment

by:pblsoft
ID: 36979342
Just to clarify: It just needs to check if the string matches any of the patterns
0
 
LVL 35

Expert Comment

by:Terry Woods
ID: 36983735
Which language/tool are you using?

I can help with creating regex patterns, but you might need someone familiar with the language you're using to help with loops etc.
0
 

Author Comment

by:pblsoft
ID: 36983975
I am working in VS 2010 /C# and am quite proficient in the language, it is only in creation of the regular expression I am short of knowledge.

Peter
0
Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

 
LVL 35

Expert Comment

by:Terry Woods
ID: 36984778
For your examples then -

- Starts with Abc and ends with 123

^Abc.*123$

- Starts with Cde and ends with 234

^Cde.*234$

- Starts with Efg and ends with 345

^Efg.*345$

The ^ matches the start of the string, and the $ matches the end. The .* matches any number of (any) characters, (including none, eg with Efg345).

I find this cheat sheet to be fantastic - the pattern modifiers are a little different for C# but the pattern syntax is otherwise pretty much the same.
0
 

Author Comment

by:pblsoft
ID: 36984840
Yes. So far so good. This is the basis. What I need to do is to "or"-combine these to one regular expression to use in one match command like:

Regex regex = new Regex("^Abc.*123$(or)^Cde.*234$(or)^Efg.*345$");

if (regex.IsMatch(myString)
  // do something

My problem is how to define the "(or)" parts, I believe it should be possible

I have seen lots of cheat sheets but haven't found this anywhere

I will be building the actual regex string in code from a list of 1 to n criteria

Peter
0
 
LVL 35

Accepted Solution

by:
Terry Woods earned 2000 total points
ID: 36989117
It's refreshing to have such a clear description of what you need! The following syntax does as you describe:

^(Abc.*123|Cde.*234|Efg.*345)$
0
 

Author Comment

by:pblsoft
ID: 36990996
Hi TerryAtOpus

Thanks al lot for your help, it was excellent. For anybody else to peruse, here is my final solution to use this in an Infragistics UltraGrid as a ColumnFilter:

        public void DoFilter()
        {
            label1.Text = "Working...";
            Application.DoEvents();
            Grid.DisplayLayout.Bands[0].ColumnFilters.ClearAllFilters();

            ColumnFilter cf = Grid.DisplayLayout.Bands[0].ColumnFilters["Key"];
            cf.FilterConditions.Clear();
            cf.LogicalOperator = FilterLogicalOperator.And;

            // _keywordsList is a list of strings to match (contains)
            if (_keywordsList != null)
                foreach (FilterCondition cfc in
                    from keyWord in _keywordsList
                    where keyWord != string.Empty
                    select new FilterCondition(FilterComparisionOperator.Contains, keyWord))
                        cf.FilterConditions.Add(cfc);

            if (FilterByNames != null)
            {
                string regEx = string.Empty;
                // Collect "or" regEx from wildcard patterns
                // Build RegEx like: ^(Abc.*123|Cde.*234|Efg.*345)$
                // Input strings are names of locations with or without wildcard
                // I.e
                // - East*Off to match EastNewOff or EastOldOff (start + end)
                // - West*On to match WestNewOn or WestOldOn (start + end)
                // - AVV to match all that contains AVV
                foreach (var searchLocation in FilterByNames)
                {
                    if (regEx == string.Empty)
                        regEx += "^(";
                    else
                        regEx += "|";
                    string filterName = searchLocation.Value.FilterName;
                    if (!filterName.Contains("*"))
                    {
                        // No wildcard in FilterName. Simple contains filter
                        regEx += ".*" + filterName + ".*";
                    }
                    else
                    {
                        // Split in two and add "startswith" and "endswith"
                        string[] parts = filterName.Split(Convert.ToChar("*"));
                        regEx += parts[0] + ".*" + parts[1];
                    }
                }
                if (regEx != string.Empty)
                {
                    regEx += ")$";
                    FilterCondition cfc = new FilterCondition(FilterComparisionOperator.Match, regEx);
                    cf.FilterConditions.Add(cfc);
                }
            }

            Grid.Rows.FilterRow.ApplyFilters();

            label1.Text = _rowCount == Grid.Rows.FilteredInRowCount
                ? string.Format("{0} items", _rowCount)
                : string.Format("{0} of {1} items (filtered)", Grid.Rows.FilteredInRowCount, _rowCount);
        }

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows a few slightly more advanced techniques for Windows 7 gadget programming, including how to save and restore user settings for your gadget and how to populate the "details" panel that is displayed in the Windows 7 gadget gallery.  …
For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question