簡體   English   中英

使用正則表達式忽略位於兩個已知單詞之間的未知單詞

[英]Using regex to ignore an unknown word that is situated between two known words

我剛剛開始學習正則表達式,但仍然有很多我不熟悉的概念。 假設我有以下字符串:

string s = "a minimum of eight (8) projects over the last five (5) years";

當它放在單詞項目的前面時,我如何忽略字符串8並提取兩個括號(8)之間的數字。 我不想提取5。

任何幫助將不勝感激。

嘗試這個:

string source = "a minimum of eight (8) projects over the last five (5) years";
Regex re = new Regex(@"\((\d+)\) projects");

var result = re.Match(source).Groups[1].Value;
// result = "8";

如果你需要一個數字,只需解析它 - int.Parse(result)

提取兩個括號之間的數字(8)

我將假設你的主要目標是提取數字。 在那種情況下,代碼

resultString = Regex.Match(subjectString, @"\d+").Value;

會給你數字(作為一個字符串)。 \\ d是數字,+表示一個或多個

我會用這樣的東西:

String matchPattern = @"a minimum of .+ \((\d+)\) projects";
String replacePattern = @"a minimum of \1 projects";
String done = Regex.Replace(source, matchPattern, replacePattern);

這將做的是將字符串中的eight (8)替換為8 ,並且它將對該位置中的任何字符串執行此操作,后面跟一個括號中的數字。

暫無
暫無

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

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