I want to check if a specific pattern (e.g. double quote) matches the exact position.
Example
string text = "aaabbb"; Regex regex = new Regex("b+");
I would like to check if regex matches exactly char 3.
I looked at the Regex.Match Method (String, Int32) , but it does not behave as I expected.
So I did some tests and some workarounds:
public void RegexTest2() { Match m; string text = "aaabbb"; int offset = 3; m = new Regex("^a+").Match(text, 0); // lets do a sanity check first Assert.AreEqual(true, m.Success); Assert.AreEqual("aaa", m.Value); // works as expected m = new Regex("^b+").Match(text, offset); Assert.AreEqual(false, m.Success); // this is quite strange... m = new Regex("^.{"+offset+"}(b+)").Match(text); // works, but is not very 'nice' Assert.AreEqual(true, m.Success); Assert.AreEqual("bbb", m.Groups[1].Value); m = new Regex("^b+").Match(text.Substring(offset)); // works too, but Assert.AreEqual(true, m.Success); Assert.AreEqual("bbb", m.Value); }
In fact, I am starting to believe that new Regex("^.", 1).Match(myString) will never match anything.
Any suggestions?
Edit:
I got a working solution (workaround). So my question is about speed and good implementation.
Simon ottenhaus
source share