Paraknight Paraknight - 5 months ago 10
Javascript Question

What RegEx would clean up this set of inputs?

I'm trying to figure out a RegEx that would match the following:

.../string-with-no-spaces
->
string-with-no-spaces


or

string-with-no-spaces:...
->
string-with-no-spaces


or

.../string-with-no-spaces:...
->
string-with-no-spaces


where ... can be anything in these example strings:

example.com:8080/string-with-no-spaces:latest
string-with-no-spaces:latest
example.com:8080/string-with-no-spaces
string-with-no-spaces


and a bonus would be

http://example.com:8080/string-with-no-spaces:latest


and all would match
string-with-no-spaces
.

Is it possible for a single RegEx to cover all those cases?

So far I've gotten as far as
/\/.+(?=:)/
but that not only includes the slash, but only works for case 3. Any ideas?

Edit: Also I should mention that I'm using Node.js, so ideally the solution should pass all of these: https://jsfiddle.net/ys0znLef/

Answer

Consider the following solution using specific regex pattern and String.match function:

var re = /(?:[/]|^)([^/:.]+?)(?:[:][^/]|$)/,
    searchString = function(str){
        var result = str.match(re);
        return result[1];
    };

console.log(searchString("example.com:8080/string-with-no-spaces"));
console.log(searchString("string-with-no-spaces:latest"));
console.log(searchString("string-with-no-spaces"));
console.log(searchString("http://example.com:8080/string-with-no-spaces:latest"));

The output for all the cases above will be string-with-no-spaces

Comments