简体   繁体   中英

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. How can this be achieved?

You can use positive look ahead to ensure the string you want to extract follows .xyz using this regex,

\S+(?=\.xyz)

Demo

Try these C# codes,

string str = "Hey Stackoverflow.xyz Whats up?";
var m = Regex.Match(str,@"\S+(?=\.xyz)");
Console.WriteLine(m.Groups[0].Value);

Outputs,

Stackoverflow

Online C# demo

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,

\S+\.xyz
/(\w+)\\.[^\W]+/

在regex101上玩

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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