Regex + Remove all text before match

后端 未结 3 1094
情书的邮戳
情书的邮戳 2020-12-19 06:05

I\'m trying to figure out a way to remove all text in a string before match in Regex. I\'m coding this in C#.

For example, if the string is \"hello, test matching\

相关标签:
3条回答
  • 2020-12-19 06:24

    *Updated, using matchcollection

    string test = "hello, test matching";
    
    string regexStrTest;
    regexStrTest = @"test\s\w+";       
    MatchCollection m1 = Regex.Matches(test, regexStrTest);
    //gets the second matched value
    string value = m1[1].Value;   
    
    0 讨论(0)
  • 2020-12-19 06:26

    For a simple solution, just replace "start-of-line anything test" with "test":

    newString = Regex.Replace(oldString, "^.*test", "test");
    

    Since * is greedy, this will replace as much as possible, i.e. a test b test c will become test c. To replace as little as possible, use *? instead of *.

    If you want to avoid duplicating the search word, you can use a Zero-width positive lookahead assertion:

    newString = Regex.Replace(oldString, "^.*(?=test)", "");
    
    0 讨论(0)
  • 2020-12-19 06:40

    You can use positive lookahead to match a string but not capture it:

    (?=test)
    

    So you want to capture the stuff before the last occurrence of test:

    ^.*(?=test)
    

    If you want to make it so that it is the first occurrence of test, use lazy matching:

    ^.*?(?=test)
    
    0 讨论(0)
提交回复
热议问题