RegEx将清理这组输入?

时间:2016-06-11 12:02:30

标签: javascript regex node.js string

我试图弄清楚符合以下条件的RegEx:

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

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

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

其中......可以是这些示例字符串中的任何内容:

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

并且奖金将是

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

并且所有内容都匹配string-with-no-spaces

单个RegEx是否可以涵盖所有这些情况?

到目前为止,我已经达到/\/.+(?=:)/,但不仅包括斜线,而且仅适用于案例3.任何想法?

编辑:另外我应该提到我使用Node.js,所以理想情况下解决方案应该通过所有这些:https://jsfiddle.net/ys0znLef/

3 个答案:

答案 0 :(得分:2)

怎么样:

(?:.*/)?([^/:\s]+)(?::.*|$)

答案 1 :(得分:1)

这是我得到的表达式...只是尝试调整以使用斜杠但不包括它。

更新的结果适用于JS

\S([a-zA-Z0-9.:/\-]+)\S
//works on regexr, regex storm, & regex101 - tested with a local html file to confirm JS matches strings

var re = /\S([a-zA-Z0-9.:/\-]+)\S/;

答案 2 :(得分:1)

使用特定的正则表达式模式和String.match函数考虑以下解决方案:

var re = /(?:[/]|^)([^/:.]+?)(?:[:][^/]|$)/,
    // (?:[/]|^) - passive group, checks if the needed string is preceded by '/' or is at start of the text
    // (?:[:][^/]|$) - passive group, checks if the needed string is followed by ':' or is at the end of the text
    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"));

上述所有情况的输出均为string-with-no-spaces