regex to find a word before and after a specific word

前端 未结 5 2126
半阙折子戏
半阙折子戏 2020-12-02 19:35

I need a regex that gives me the word before and after a specific word, included the search word itself.

Like: \"This is some dummy text to find a word\" sh

相关标签:
5条回答
  • 2020-12-02 20:02

    EDIT:

    If you want to grab all the content from the space before first word to the space after the word use:

    (?:\S+\s)?\S*text\S*(?:\s\S+)?
    

    A simple tests:

    string input = @"
        This is some dummy text to find a word in a string full with text and words
        Text is too read
        Read my text.
        This is a text-field example
        this is some dummy la@text.be to read";
    
    var matches = Regex.Matches(
        input,
        @"(?:\S+\s)?\S*text\S*(?:\s\S+)?",
        RegexOptions.IgnoreCase
    );
    

    the matches are:

    dummy text to
    with text and
    Text is
    my text.
    a text-field example
    dummy la@text.be to
    0 讨论(0)
  • 2020-12-02 20:24
    /[A-Za-z'-]+ text [A-Za-z'-]+/
    

    Should work in most cases, including hyphenated and compound words.

    0 讨论(0)
  • 2020-12-02 20:24
    ([A-z]+) text ([A-z]+)
    

    would do nicely

    0 讨论(0)
  • 2020-12-02 20:27
    //I prefer this style for readability
    
    string pattern = @"(?<before>\w+) text (?<after>\w+)";
    string input = "larry text bob fred text ginger fred text barney";
    MatchCollection matches = Regex.Matches(input, pattern);
    
    for (int i = 0; i < matches.Count; i++)
    {
        Console.WriteLine("before:" + matches[i].Groups["before"].ToString());
        Console.WriteLine("after:" + matches[i].Groups["after"].ToString());
    } 
    
    /* Output:
    before:larry
    after:bob
    before:fred
    after:ginger
    before:fred
    after:barney
    */
    
    0 讨论(0)
  • 2020-12-02 20:27

    [a-zA-Z]+\stext\s[a-zA-Z]+

    I believe this will work nicely

    0 讨论(0)
提交回复
热议问题