gpt4 book ai didi

c# - 使用 C# 测试字符串是否包含在 [brackets] 中的正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:33 25 4
gpt4 key购买 nike

我的字符串可能包含也可能不包含在括号中

string a = "[Hello world]";
string b = "Hello world";

只要字符串包含 [],下面的正则表达式就会返回 true,但这不是目标:)

var c = "hello[ ]world";
var isCommandArray = Regex.IsMatch(c, @"\[.*?\]"); // returns true

谢谢

最佳答案

如果允许其他括号在中间,则不必使用Regex:

bool isBracketed = s.StartsWith("[") && s.EndsWith("]");

如果您不允许中间有其他括号,您仍然可以这样做:

bool isBracketed = s.LastIndexOf("[") == 0 && s.IndexOf("]") == s.Length - 1;

关于c# - 使用 C# 测试字符串是否包含在 [brackets] 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14111914/

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