Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以使用正则表达式来查找X的索引吗?_C#_Regex - Fatal编程技术网

C# 我可以使用正则表达式来查找X的索引吗?

C# 我可以使用正则表达式来查找X的索引吗?,c#,regex,C#,Regex,我有一个大字符串,想找到X的第一个匹配项,X是“numberXnumber”。。。3X3或4X9 我怎样才能在C#中做到这一点?这可能会对您有所帮助 string myText = "33x99 lorem ipsum 004x44"; //the first matched group index int firstIndex = Regex.Match(myText,"([0-9]+)(x)([0-9]+)").Index; //first matche

我有一个大字符串,想找到X的第一个匹配项,X是“numberXnumber”。。。3X3或4X9

我怎样才能在C#中做到这一点?

这可能会对您有所帮助

   string myText = "33x99 lorem ipsum  004x44";

    //the first matched group index
    int firstIndex =  Regex.Match(myText,"([0-9]+)(x)([0-9]+)").Index;

    //first matched "x" (group = 2) index 
    int firstXIndex =  Regex.Match(myText,"([0-9]+)(x)([0-9]+)").Groups[2].Index;

是的,regex可以帮你


如果您知道数字是唯一的一位数,您可以选择
([0-9]+)X([0-9]+)
,您想要数字还是数字的索引?你可以得到这两个,但你可能会想看看

如果只需要单个数字(89x72只匹配9x7),实际模式将是
[0-9]x[0-9]
,或者
[0-9]+x[0-9]+
匹配两个方向上最长的连续数字串。

您可以使用以下模式:

\d([xX])\d

如果我测试

Blaat3x3测试

我得到:

匹配偏移量:5匹配长度:3 匹配文本:3X3第1组偏移量:6 第1组长度:1第1组文字:X

另请看一看
NextMatch
,这是一个方便的功能

match = match.NextMatch();
match.Value; // 1X3;

对于那些喜欢扩展方法的人:

public static int RegexIndexOf(this string str, string pattern)
{
    var m = Regex.Match(str, pattern);
    return m.Success ? m.Index : -1;
}
match = match.NextMatch();
match.Value; // 1X3;
public static int RegexIndexOf(this string str, string pattern)
{
    var m = Regex.Match(str, pattern);
    return m.Success ? m.Index : -1;
}