简体   繁体   中英

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?

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

如果只需要第一个点之后的部分,则根本不需要正则表达式:

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

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