[英]How to extract a word which is having an extension from a string using regex?
I need to extract a word from a string before an extension. 我需要在扩展名之前从字符串中提取一个单词。 Let's say I've got a string like :
假设我有一个类似的字符串:
"Hey Stackoverflow.xyz Whats up?"
I need to extract a word with extension .xyz ie Stackoverflow. 我需要提取一个扩展名为.xyz的单词,即Stackoverflow。 How can this be achieved?
如何做到这一点?
You can use positive look ahead to ensure the string you want to extract follows .xyz
using this regex, 您可以使用积极的前瞻性来确保要提取的字符串使用此正则表达式遵循
.xyz
,
\S+(?=\.xyz)
Try these C# codes, 试试这些C#代码,
string str = "Hey Stackoverflow.xyz Whats up?";
var m = Regex.Match(str,@"\S+(?=\.xyz)");
Console.WriteLine(m.Groups[0].Value);
Outputs, 输出,
Stackoverflow
In case you want to extract your string with extension Stackoverflow.xyz
, just change the look ahead part of regex to normal string like this, 如果您想使用扩展名
Stackoverflow.xyz
提取字符串,只需将regex的前瞻部分更改为普通字符串,如下所示,
\S+\.xyz
/(\w+)\\.[^\W]+/
Use the following regex to extract the word you need before the extension 使用以下正则表达式提取扩展名之前需要的单词
\s(.*)?\.
Here the word will be captured using the brackets. 此处将使用方括号捕获单词。
string str = "Hey Stackoverflow.xyz Whats up?";
var regexResult = Regex.Match(str,@"\s(.*)?\.");
Console.WriteLine(regexResult.Groups[1].Value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.