c# - 使用正则表达式拆分字符串

标签 c# asp.net .net regex c#-4.0

我有以下格式的字符串:

string test = "test.BO.ID";

我的目标是将字符串的第一个点之后的部分字符串化。 所以理想情况下,我期望输出为 "BO.ID"。

这是我尝试过的:

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

我得到的输出是空的。

我需要为 Regex 做哪些修改?

最佳答案

你得到一个空输出,因为你的模式可以匹配字符串开头的空字符串,这就足够了,因为 .*? 是惰性子模式,而 . 匹配任何字符。

使用(值将在 Match.Groups[1].Value 中)

\.(.*)

或(通过前瞻,将字符串作为 Match.Value)

(?<=\.).*

参见 regex demo和一个 C# online demo .

非正则表达式方法可以使用 String#Splitcount 参数(demo):

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

关于c# - 使用正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042633/

相关文章:

c# - Array 的通用替代品是什么?

c# - 将 C# GUI 组件封装在 DLL 中

c# - 我是否需要 web.config 值配置 -> 运行时 -> System.Web.Extensions 的 assemblyBinding?

c# - 将ReadProcessMemory输出转换为字符串

c# - LINQ - 向数据上下文添加函数

Javascript 变量看起来像是被赋值了,但实际上并没有

asp.net - 如何在 Windows Azure Web 角色中进行 DNS 查找?

.net - Team Foundation Server 生成变量

c# - C# 28 次内联限制是否有解决方法?

c# - 如何在 asp.net 中使用 System.Web.Caching?