gpt4 book ai didi

c# - 如何使用 C# 提取括号之间的所有字符串?

转载 作者:行者123 更新时间:2023-11-30 13:35:39 24 4
gpt4 key购买 nike

如果我有一个字符串,例如:

“你的id是(1),你的号码是(0000000000)”

将这些字符串提取到字符串列表中的最佳方法是什么。括号之间的数字可以增加位数,因此搜索括号之间的字符串是一种更好的技术。

我可以使用下面的代码来提取括号之间的第一个字符串。

var myString = "You id is (1) and your number is (0000000000)";
var firstNumberBetweenBrackets = myString.Split('(', ')')[1]; // would return 1

最佳答案

这是一个 LINQ 解决方案:

var result = myString.Split().Where(x => x.StartsWith("(") && x.EndsWith(")")).ToList();

存储在 result 中的值:

result[0] = (1)
result[1] = (0000000000)

如果您只想要不带括号的数字,请使用:

var result = myString.Split().Where(x => x.StartsWith("(") && x.EndsWith(")"))
.Select(x=>x.Replace("(", string.Empty).Replace(")", string.Empty))
.ToList();

存储在 result 中的值:

result[0] = 1
result[1] = 0000000000

关于c# - 如何使用 C# 提取括号之间的所有字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48972999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com