2016-06-11 34 views
-1

我試圖找出一個正則表達式,將符合下列條件:什麼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

是否有可能爲一個單一的正則表達式來涵蓋所有這些情況?

到目前爲止,我已經儘可能/\/.+(?=:)/得到但這不僅包括斜槓,但只適用於情況3.任何想法?

編輯:我還想說,我使用Node.js的,所以理想的解決方案應該通過所有這些:https://jsfiddle.net/ys0znLef/

+0

有什麼東西永遠在那裏確定? –

+0

只有'沒有空格的字符串'。如果知道正則表達式並且可以將我需要的正則表達式轉換成英語,那麼它將是「刪除http://如果它存在,那麼在斜槓前刪除所有內容(如果有的話),然後在冒號後刪除所有內容。 –

回答

2

如何:

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

缺少轉義字符,它仍然匹配空格。 –

+0

@SteveKline:什麼逃生角色?否定字符類確保我們沒有任何字符串中的空格。或者我錯過了什麼? – Toto

+0

@ rock321987剛剛說的是一樣的。爲了澄清,表達最好應該通過所有這些測試:https://jsfiddle.net/ys0znLef/ –

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/; 
+0

這對於提供的測試用例不起作用。 – Toto

+0

嘗試在這裏:https://regex101.com/r/cI7fW0/1 – Toto

+0

似乎像JS不支持在那裏的一切。我在測試用例中獲得了三個不同的匹配:https://jsfiddle.net/zd6s50e9/另外我在那裏看到一個「com」我忘了提到頂級域名可以是任何。也許一個測試用例應該是.org左右。 –

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

+0

輝煌!你能分解那裏發生的事情嗎?只是讓我更瞭解它?結果如何?[1]?從我所看到的結果來看,有時result.length也可能很高。 –

+1

@Paraknight增加了一些解釋。另外,不要擔心'result.length',在任何情況下都會是'2' – RomanPerekhrest

+1

謝謝,我真的很感謝你的解釋,但是我意識到@Toto擊敗了你,並且我沒有意識到它,所以這就是我接受他們的答案而不是你的答案的原因。 –