Skip to content

Instantly share code, notes, and snippets.

@wisehackermonkey
Created July 16, 2020 18:51
Show Gist options
  • Save wisehackermonkey/963f6b211454452a95af55a62c85d166 to your computer and use it in GitHub Desktop.
Save wisehackermonkey/963f6b211454452a95af55a62c85d166 to your computer and use it in GitHub Desktop.
how to detect python, java, c programming languages using regex

hacker rank example

function trim(s){ 
  return ( s || '' ).replace( /^\s+|\s+$/g, '' ); 
}
function processData(input) {
            input = trim(input)

    var split = input.split('\n');
    split.shift();
    //regexr.com/58j2m
    var regex_java = RegExp(/(public|java|static|System|println)/);
    // regexr.com/58j16
    let regex_python = RegExp(/(print\s"?|def\s\w+:|__\w{3,4}__|None|\(self\.?|class\s\w+:\n)/)
    // regexr.com/58j2s
    let regex_c = RegExp(/(#include<.+>\n|int\smain\(\)|\/\*.+\*\/)/)
    // split.forEach(function (item) {
        if(regex_java.test(input)){
        console.log("Java");
        }else if(regex_python.test(input)){
        console.log("Python");
        }else if(regex_c.test(input)){

        console.log("C");
        }
    // });
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment