Note that there are some explanatory texts on larger screens.

plurals
  1. POUnusual Regex behavior in c#
    text
    copied!<p>I have a Regex that is behaving rather oddly and I can't figure why. Original Regex:</p> <pre><code>Regex regex = new Regex(@"(?i)\d\.\d\dv"); </code></pre> <p>This expression returns/matches an equivalent to 1.35V or 1.35v, which is what I want. However, it is not exclusive enough for my program and it returns some strings I don't need.</p> <p>Modified Regex:</p> <pre><code>Regex rgx = new Regex(@"(?i)\d\.\d\dv\s"); </code></pre> <p>Simply by adding '\s' to the expression, it matches/returns DDR3, which is not at all what I want. I'm guessing some sort of inversion is occurring, but I don't understand why and I can't seem to find a reference to explain it. All I wanted to do was add a space to the end of expression to filter a few more results.</p> <p>Any help would be greatly appreciated.</p> <p>EDIT: Here is a functional test case with a generic version of what is going on in my code. Just open a new WPF in Visual Studio, copy and paste, and it should repeat the results for you.</p> <pre><code>namespace WpfApplication1 { /// &lt;summary&gt; /// Interaction logic for MainWindow.xaml /// &lt;/summary&gt; public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } Regex rgx1 = new Regex(@"(?i)\d\.\d\dv"); Regex rgx2 = new Regex(@"(?i)\d\.\d\dv\s"); string testCase = @"DDR3 Vdd | | | | | 1.35v |"; string str = null; public void IsMatch(string input) { Match rgx1Match = rgx1.Match(input); if (rgx1Match.Success) { GetInfo(input); } } public void GetInfo(string input) { Match rgx1Match = rgx1.Match(input); Match rgx2Match = rgx2.Match(input); string[] tempArray = input.Split(); int index = 0; if (rgx1Match.Success) { index = GetMatchIndex(rgx1, tempArray); str = tempArray[index].Trim(); global::System.Windows.Forms.MessageBox.Show("First expression match: " + str); } if (rgx2Match.Success) { index = GetMatchIndex(rgx2, tempArray); str = tempArray[index].Trim(); System.Windows.Forms.MessageBox.Show(input); global::System.Windows.Forms.MessageBox.Show("Second expression match: " + str); } } public int GetMatchIndex(Regex expression, string[] input) { int index = 0; for (int i = 0; i &lt; input.Length; i++) { if (index &lt; 1) { Match rgxMatch = expression.Match(input[i]); if (rgxMatch.Success) { index = i; } } } return index; } private void button1_Click(object sender, RoutedEventArgs e) { string line; IsMatch(testCase); } } </code></pre> <p>}</p> <p>The GetMatchesIndex method is called a number of times in other parts of the code without incident, it is just on this one Regex that I've hit a stumbling block.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload