Showing posts with label Regular Expression. Show all posts
Showing posts with label Regular Expression. 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

Real Time Web Analytics