Showing posts with label Regex. Show all posts
Showing posts with label Regex. Show all posts

Friday, May 27, 2016

Word Boundaries Regex

\b

This is the second time this week where I have had to ask myself "how did I not know about this?"

There is a regex character to identify word boundaries: \b This is a zero length match, similar to the caret and dollar sign. It finds the boundaries between words, allowing you to search for a whole word match.

Below is a sample extension method that uses this to replace words in a string.

Implementation

public static class StringExtensions
{
    private static readonly Regex WordRegex = new Regex(@"\b\w+\b", RegexOptions.Compiled);
 
    public static string ReplaceWords(
        this string input,
        string find,
        string replace,
        StringComparison comparison = StringComparison.InvariantCulture)
    {
        return WordRegex.Replace(input, m => m.Value.Equals(find, comparison)
            ? replace
            : m.Value);
    }
}

Saturday, December 19, 2015

Group Regex Replace in Visual Studio

Wow, I cannot believe that I did not know about this until now!

We all know that you can use regular expressions to search for things in a document, and we all know that you can replace those matches, but did you know that you can use group matches from your regex in the replace value? Because you can, and it is amazingly useful!

Example: Your class has properties with one attribute containing a value, and you want to add another attribute with the same value.

Find: \[Description\("(\w+)"\)\]

public class MyClass
{
    [Description("A"), DisplayName("A")]
    public string A { get; set; }
 
    [Description("B")]
    public string B { get; set; }
 
    [Description("C")]
    public string C { get; set; }
}

Replace: [Description("$1"), DisplayName("$1")

public class MyClass
{
    [Description("A"), DisplayName("A")]
    public string A { get; set; }
 
    [Description("B"), DisplayName("B")]
    public string B { get; set; }
 
    [Description("C"), DisplayName("C")]
    public string C { get; set; }
}

Enjoy,
Tom

Sunday, December 14, 2014

How much does RegexOptions.Compiled improve performance in .NET?

Just how much does the RegexOptions.Compiled flag improve regular expression performance in .NET? The answer: a lot! People have spoken about this before, but below are some more numbers to how you just how much it matters!

Performance Stats

Character Count Regex Pattern
1
[a-z]
3
[b-y].[1-8]
5
[b-y].[c-x].[1-8].[2-7]
7
[b-y].[c-x].[d-w].[1-8].[2-7].[3-6]
9
[b-y].[c-x].[d-w].[e-v].[1-8].[2-7].[3-6].[4-5]

RegexOptions 1 3 5 7 9
None 234176 285067 653016 690282 687343
Compiled 193945 235213 430609 452483 454625
Percent Gain 17% 17% 34% 34% 34%

Real Time Web Analytics