简体   繁体   English

使用正则表达式分割字符串

[英]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". 因此,理想情况下,我期望输出为“ 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 ) 使用(该值将在Match.Groups[1].Value

\.(.*)

or (with a lookahead, to get the string as a Match.Value ) 或(先行查找,以将字符串作为Match.Value

(?<=\.).*

See the regex demo and a C# online demo . 请参阅regex演示C#在线演示

A non-regex approach can be use String#Split with count argument ( demo ): 非正则表达式方法可以与带有count参数( demo )的String#Split一起使用:

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('.'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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