Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i use regex to find the index of X?

Tags:

c#

regex

I have a big string, and want to find the first occurrence of X, X is "numberXnumber"... 3X3, or 4X9...

How could i do this in C#?

like image 250
Jason94 Avatar asked Apr 08 '11 07:04

Jason94


People also ask

How do I find a star in regex?

* in Regex means: Matches the previous element zero or more times. so that, you need to use \* or [*] instead.

What does * do in regex?

The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.

What is the regex for special characters?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "."

What does \\ mean in regex?

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.


1 Answers

var s = "long string.....24X10     .....1X3";
var match = Regex.Match(s, @"\d+X\d+");
if (match.Success) {
    Console.WriteLine(match.Index); // 16
    Console.WriteLine(match.Value); // 24X10;
}

Also take a look at NextMatch which is a handy function

match = match.NextMatch();
match.Value; // 1X3;
like image 96
James Kyburz Avatar answered Sep 28 '22 18:09

James Kyburz