簡體   English   中英

正則表達式以匹配單詞和句點

[英]Regex to match between a word and period

我想知道是否有人可以幫助我完成正則表達式。 我正在嘗試將關鍵字(詞組)之后的文本與句子結尾的句點匹配。 我很親密,但是,無論我嘗試什么,總是要包括那個時期。

這是我目前所在的位置:

phrase([^.]+?)\.

我知道我以后可能會做這樣的事情:

string.replace(".",""); 

但是,我寧願通過正則表達式執行我需要的所有操作。 有人可以告訴我我缺少什么部分嗎?

例:

  • 輸入: "The current phrase blah blah blah."
  • 預期輸出: "blah blah blah"
  • 當前輸出: "blah blah blah." (包括期間。)

您需要使用正則表達式並從中獲取Groups[1].Value

var s = "My phrase is here.";
var rx = new Regex(@"phrase([^.]+)\.");
Console.WriteLine(rx.Match(s).Groups[1].Value);

觀看演示

或重新編寫帶有正則表達式的正則表達式,並使用rx.Match(s).Value訪問所需的文本:

(?<=phrase)[^.]+

碼:

var rx = new Regex(@"(?<=phrase)[^.]+");
Console.WriteLine(rx.Match(s).Value);

正則表達式演示

注意 :回顧是消耗資源的,我絕對希望使用捕獲組方法。

var blahs = Regex.Match(input, @"phrase(.+?)\.").Groups[1].Value;

Lookbehinds and lookaheads您可以在其他文本之前/之后匹配文本, 但不包括其他文本。 在您的示例中,您需要(?<=The current phrase ).*?(?=\\.)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM