I wondering if anyone can help me finish a regex. I am trying to match the text after a keyword (phrase) and the period at the end of the sentence. I am close, but, no matter what I try, that period is always included.
Here is where I am currently:
phrase([^.]+?)\.
I know I could probably do something afterward like this:
string.replace(".","");
However, I would rather do everything I need via the regular expression. Can someone show me what part I am missing?
Example:
"The current phrase blah blah blah."
"blah blah blah"
"blah blah blah."
(period included.) You need to either use your regex and get the Groups[1].Value
from it:
var s = "My phrase is here.";
var rx = new Regex(@"phrase([^.]+)\.");
Console.WriteLine(rx.Match(s).Groups[1].Value);
See demo
Or re-write a regex with a look-behind and access the text you need using rx.Match(s).Value
:
(?<=phrase)[^.]+
Code:
var rx = new Regex(@"(?<=phrase)[^.]+");
Console.WriteLine(rx.Match(s).Value);
See regex demo
NOTE : Look-behinds are resource-consuming, I'd definitely prefer the capturing group approach.
var blahs = Regex.Match(input, @"phrase(.+?)\.").Groups[1].Value;
Lookbehinds and lookaheads
will allow you to match text before/after some other text, but not including the other text. In your example, you'll want (?<=The current phrase ).*?(?=\\.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.