این محتوا تنها در این زبانها موجود است: عربي, English, Español, Français, Italiano, 日本語, Русский, Українська, Oʻzbek, 简体中文. لطفاً به ما
Find programming languages
There are many programming languages, for instance Java, JavaScript, PHP, C, C++.
Create a regexp that finds them in the string Java JavaScript PHP C++ C:
let regexp = /your regexp/g;
alert("Java JavaScript PHP C++ C".match(regexp)); // Java JavaScript PHP C++ C
The first idea can be to list the languages with | in-between.
But that doesn’t work right:
The regular expression engine looks for alternations one-by-one. That is: first it checks if we have Java, otherwise – looks for JavaScript and so on.
As a result, JavaScript can never be found, just because Java is checked first.
The same with C and C++.
There are two solutions for that problem:
- Change the order to check the longer match first:
JavaScript|Java|C\+\+|C|PHP. - Merge variants with the same start:
Java(Script)?|C(\+\+)?|PHP.
In action: