简体   繁体   English

正则表达式以匹配单词和句点

[英]Regex to match between a word and period

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: 例:

  • Input: "The current phrase blah blah blah." 输入: "The current phrase blah blah blah."
  • Expected output: "blah blah blah" 预期输出: "blah blah blah"
  • Current output: "blah blah blah." 当前输出: "blah blah blah." (period included.) (包括期间。)

You need to either use your regex and get the Groups[1].Value from it: 您需要使用正则表达式并从中获取Groups[1].Value

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 : 或重新编写带有正则表达式的正则表达式,并使用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. Lookbehinds and lookaheads您可以在其他文本之前/之后匹配文本, 但不包括其他文本。 In your example, you'll want (?<=The current phrase ).*?(?=\\.) 在您的示例中,您需要(?<=The current phrase ).*?(?=\\.)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM