0

Why does the following Regex return two matches?

Regex: [^,]*

Input: AB

Output (Two matches):

|AB| ||

I am expecting only one match, AB

I tried it in a couple of Regex testers, it's not a language specific issue.

Test it here: https://regex101.com/r/fjT79V/2

Sample code (Java):

public static void main(String[] args) {
    Pattern p = Pattern.compile("[^,]*");
    Matcher m = p.matcher("AB");

    while (m.find()) 
        System.out.println("|" + m.group() + "|");
}
Jennifer P.
  • 377
  • 1
  • 3
  • 17
  • Is it possible to achieve one match on empty string and one match on 'AB' using the same regex? `+` will not match the empty string. This is part of a bigger regex: `([^,]*,?)` should have two matches on `AB,CD`, but has 3 matches: `AB`, `CD`, and empty string. – Jennifer P. Nov 09 '17 at 10:28
  • It should return two matches, but it returns 3: `AB,` and then `CD` and then empty string. – Jennifer P. Nov 10 '17 at 14:28
  • This answer is not correct, and this question is not the duplicate it is marked. The correct answer is in this question: https://stackoverflow.com/questions/47296146/how-to-parse-comma-separated-line-correctly-with-regex `[^,]+|(?<=,)` – Jennifer P. Nov 14 '17 at 23:14

0 Answers0