regex javascript正则表达式用于wss,ws http和https

e3bfsja2  于 2023-01-31  发布在  Java
关注(0)|答案(1)|浏览(153)

我需要在JavaScript中使用regex从字符串中检索这些URL
下面是一个示例字符串:

"Hello everyone! please join us at: https://oursite.com/. and 
please visit our courses websites: http://courseone.com.eu & http://coursetwo.us. 
For prod use websocket with this url: wss://localhost:4500/websocket/. and 
for staging use this url: ws://localhost:4500/websocket".

现在我想从上面的字符串中提取这些URL:
就像这样:

https://oursite.com/
http://courseone.com.eu
http://coursetwo.us
wss://localhost:4500/websocket/
ws://localhost:4500/websocket

现在我按照Detect URLs in text with JavaScript中给出的正则表达式

/(https?:\/\/[^\s]+)/g;

但它对我来说不太合适,因为我也有wsswsURL
有人能帮我做正则表达式吗?

dfuffjeb

dfuffjeb1#

在您的模式中使用此部分[^\s]+匹配过多。
根据您希望在链接中允许的格式和字符,您可以通过匹配可选的非空格字符,然后以非."结尾,从问题中获得所需的结果

\b(?:http|ws)s?:\/\/\S*[^\s."]

Regex demo

const regex = /\b(?:http|ws)s?:\/\/\S*[^\s."]/g;
const s = `"Hello everyone! please join us at: https://oursite.com/. and 
please visit our courses websites: http://courseone.com.eu & http://coursetwo.us. 
    For prod use websocket with this url: wss://localhost:4500/websocket/. and 
    for staging use this url: ws://localhost:4500/websocket".`

console.log(s.match(regex));

或者,在单词字符后跟可选正斜杠处结束匹配:

\b(?:http|ws)s?:\/\/\S*\w\/?

Regex demo

相关问题