Note that there are some explanatory texts on larger screens.

plurals
  1. POregex to test for correct use of commas
    primarykey
    data
    text
    <p>I'm looping through thousands of strings with various regexes to check for simple errors. I would like to add a regex to check for the correct use of commas.</p> <p>If a comma exists in one of my strings, then it MUST be followed by either whitespace or exactly three digits:</p> <ul> <li>valid: ,\s</li> <li>valid: ,\d\d\d</li> </ul> <p>But if a comma is followed by any other pattern, then it is an error:</p> <ul> <li>invalid: ,\D</li> <li>invalid: ,\d</li> <li>invalid: ,\d\d</li> <li>invalid: ,\d\d\d\d</li> </ul> <p>The best regex I've come up with thus far is:</p> <p><code> Regex CommaError = new Regex(@",(^(\d\d\d)|\S)"); // fails case #2 </code></p> <p>To test, I am using:</p> <pre><code>if (CommaError.IsMatch(", ")) // should NOT match Console.WriteLine("failed case #1"); if (CommaError.IsMatch(",234")) // should NOT match Console.WriteLine("failed case #2"); if (!CommaError.IsMatch("0,a")) // should match Console.WriteLine("failed case #3"); if (!CommaError.IsMatch("0,0")) // should match Console.WriteLine("failed case #4"); if (!CommaError.IsMatch("0,0a1")) // should match Console.WriteLine("failed case #5"); </code></pre> <p>But the regex I gave above fails case #2 (it matches when it should not).</p> <p>I've invested several hours investigating this, and searched the Web for similar regexes, but have hit a brick wall. What's wrong with my regex?</p> <p>Update: Peter posted a comment with a regex that works the way I want:</p> <pre><code>Regex CommaError = new Regex(@",(?!\d\d\d|\s)"); </code></pre> <p>Edit: Well, almost. It fails in this case:</p> <pre><code>if (!CommaError.IsMatch("1,2345")) // should match Console.WriteLine("failed case #6"); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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