从正则表达式&在c#中删除括号

本文关键字:删除 正则表达式 | 更新日期: 2023-09-27 18:02:35

我正在尝试采用HTML字符串并匹配[image, h, w]的实例,其中h和w是可以高达1200的整数。

这是我第一次尝试学习正则表达式。以下是目前为止的内容:

Regex r = new Regex(@"'Image, ('d+?), ('d+?)']");
Match match = r.Match(controlText);

但是在我的regex测试器中,它没有选择最后一个括号,并且在我的代码中,它不匹配它应该匹配的字符串。

所以我想要的输出是'image, h, w',从那里我想要解析h &并将它们存储在。

我是一名初级开发人员,在我的第一份工作的第二周,我想我花了太多的时间来弄清楚这一点。

从正则表达式&在c#中删除括号

Tuple<int, int>[] imageSizes =
    (from Match match
        in new Regex(@"'[image, ('d+), ('d+)']").Matches(controlText) 
     select new Tuple<int, int>(
        int.Parse(match.Groups[1].Value),
        int.Parse(match.Groups[2].Value))).ToArray();

示例:string controlText = "[image, 1200, 100]abacaldjfal; jk[image, 289, 400]";

imageSizes将变成[1200, 100], [289, 400]

Edit:由于这个标记似乎只有一个实例,您可以只做以下操作:

Match match = new Regex(@"'[image, ('d+), ('d+)']").Match(controlText);
int h = int.Parse(match.Groups[1].Value);
int w = int.Parse(match.Groups[2].Value);

示例:string controlText = "[image, 1200, 100]abcadjfklajdfad;afdh";

h1200, w100

这就是我的方法…

var text = "[image, 300, 200] ........";
var regex = new Regex("''[Image, (''d+?), (''d+?)'']", RegexOptions.IgnoreCase );
var match = regex.Match( text );
if (match.Success){
    var h = int.Parse(match.Groups[1].Value);
    var w = int.Parse(match.Groups[2].Value);
}