user2630764
user2630764

Reputation: 622

Splitting of a string using Regex

I have string of the following format:

string test = "test.BO.ID";

My aim is string that part of the string whatever comes after first dot. So ideally I am expecting output as "BO.ID".

Here is what I have tried:

// Checking for the first occurence and take whatever comes after dot
var output = Regex.Match(test, @"^(?=.).*?"); 

The output I am getting is empty.

What is the modification I need to make it for Regex?

Upvotes: 1

Views: 52

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You get an empty output because the pattern you have can match an empty string at the start of a string, and that is enough since .*? is a lazy subpattern and . matches any char.

Use (the value will be in Match.Groups[1].Value)

\.(.*)

or (with a lookahead, to get the string as a Match.Value)

(?<=\.).*

See the regex demo and a C# online demo.

A non-regex approach can be use String#Split with count argument (demo):

var s = "test.BO.ID";
var res = s.Split(new[] {"."}, 2, StringSplitOptions.None);
if (res.GetLength(0) > 1)
    Console.WriteLine(res[1]);

Upvotes: 4

Dawnkeeper
Dawnkeeper

Reputation: 2873

If you only want the part after the first dot you don't need a regex at all:

x.Substring(x.IndexOf('.'))

Upvotes: 3

Related Questions