c#提取以%!开头的单词和以!%结尾

本文关键字:结尾 单词 开头 提取 | 更新日期: 2023-09-27 18:13:53

如果单词以%开头,我需要从一段文本中提取一些单词!并以结尾!%

我想象regex会很好,但不幸的是我的regex不是那么好…好吧,这很糟糕……好吧,它不存在:(.

示例文本

You don't want no %!beef!%, boy
Know I run the streets, boy
Better follow me towards
Downtown
What you see is what you get %!girl!%
Don't ever forget girl
Ain't seen nothing yet until you're
%!Downtown!%

预期结果

beef, girl, Downtown

如何在c#中使用或不使用正则表达式实现此功能?

c#提取以%!开头的单词和以!%结尾

像这样:

var reg = new Regex(@"%!(?<word>'w+)!%");
var inStr = @"You don't want no %!beef!%, boy
Know I run the streets, boy
Better follow me towards
Downtown
What you see is what you get %!girl!%
Don't ever forget girl
Ain't seen nothing yet until you're
%!Downtown!%";
var results = reg.Matches(inStr).Cast<Match>().Select(m => m.Groups["word"].Value);

这将给你一个匹配的单词列表。将其转换为逗号分隔的字符串是一个练习,我将留给您。

而且,下次你可能应该做一些快速的研究,你最终将不得不学习简单的正则表达式。