As the result, the regular expression never finds the closing bracket:Ĭonsole.log(/]/.test(']')) // outputs false This won't work in JavaScript because the first ] is interpreted as the end of the character class there, so the same regular expression in JavaScript means an empty character class that never matches, followed by a closing bracket. Matched, err := regexp.MatchString(`]`, "]") Print(re.match(']', ']')) # outputs the Match object In these languages, you can put the closing bracket right after the opening bracket to avoid escaping the former:Įcho preg_match('/]/', ']', $m) ? 'Match ' : 'No match' // Outputs 'Match' Re.compile('') # throws "unterminated character set" Emits a warning: preg_match(): Compilation failed: missing terminating ] for character classĮcho preg_match('//', ']') ? 'Match ' : 'No match' PatternSynta圎xception e = assertThrows(PatternSynta圎xception.class,ĪssertEquals("Unclosed character class", e.getDescription()) However, in Java, PHP (PCRE), Go, and Python, the same regex throws an exception: This is a valid JavaScript code, and it always prints false regardless of the value of str: Popular regex engines treat the empty brackets differently. But what happens if the character class is empty? When using character classes, you can specify the allowed characters in brackets, such as or. This time, it's about a regex that never matches. I contributed to PCRE and wrote two smaller regular expression engines, but I still regularly learn something new about this topic. Empty character class in JavaScript regexes
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |