简体   繁体   English

我的正则表达式与数字不匹配

[英]My regex does not match numbers

I am new at making regular expressions, and so this might just be a stupid oversight, but my regex (that aims to match URL's) is not working. 我是制作正则表达式的新手,所以这可能只是一个愚蠢的疏忽,但我的正则表达式(旨在匹配URL的)是行不通的。 My goal was to have it match any urls like: 我的目标是让它匹配任何网址,如:

http://www.somewhere.com
somewhere.com
https://ww3.some_where-hi.com
www.goop.go/herp/derp.lol

The regex i built is below, however, it does not match a URL like http://t.co/GZhtBh6c , it stops matching at the number 6 (As determined by www.regexpal.com ). 我构建的正则表达式在下面,但它与http://t.co/GZhtBh6c这样的URL不匹配,它在数字6处停止匹配(由www.regexpal.com确定)。

((http|https)://)?([a-z0-9]+\.)?[a-z0-9\-_]+.[a-z]+(/[a-z0-9\-_]*)*([a-z0-9\-_]*\.[a-z]+){0,1}

Can anyone tell me why this is not working? 谁能告诉我为什么这不起作用? Also, I'm sure this is not the best solution. 此外,我确信这不是最好的解决方案。 If you have a more elegant regex for this, I would love to see it. 如果你有一个更优雅的正则表达式,我很乐意看到它。

PS This regex will be used with javascript. PS这个正则表达式将与JavaScript一起使用。

Validate if a string holds a URL as specified in RFC 3986. Both absolute and relative URLs are supported. 验证字符串是否包含RFC 3986中指定的URL。支持绝对和相对URL。

This matches your provide sample and more. 这符合您提供的样本等。 It also lets you extract the different parts of the url 它还允许您提取URL的不同部分

^
(# Scheme
 [a-z][a-z0-9+\-.]*:
 (# Authority & path
  //
  ([a-z0-9\-._~%!$&'()*+,;=]+@)?              # User
  ([a-z0-9\-._~%]+                            # Named host
  |\[[a-f0-9:.]+\]                            # IPv6 host
  |\[v[a-f0-9][a-z0-9\-._~%!$&'()*+,;=:]+\])  # IPvFuture host
  (:[0-9]+)?                                  # Port
  (/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/?          # Path
 |# Path without authority
  (/?[a-z0-9\-._~%!$&'()*+,;=:@]+(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/?)?
 )
|# Relative URL (no scheme or authority)
 ([a-z0-9\-._~%!$&'()*+,;=@]+(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/?  # Relative path
 |(/[a-z0-9\-._~%!$&'()*+,;=:@]+)+/?)                            # Absolute path
)
# Query
(\?[a-z0-9\-._~%!$&'()*+,;=:@/?]*)?
# Fragment
(\#[a-z0-9\-._~%!$&'()*+,;=:@/?]*)?
$

In javascript this becomes 在javascript中,这变成了

if (/^([a-z][a-z0-9+\-.]*:(\/\/([a-z0-9\-._~%!$&'()*+,;=]+@)?([a-z0-9\-._~%]+|\[[a-f0-9:.]+\]|\[v[a-f0-9][a-z0-9\-._~%!$&'()*+,;=:]+\])(:[0-9]+)?(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?|(\/?[a-z0-9\-._~%!$&'()*+,;=:@]+(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?)?)|([a-z0-9\-._~%!$&'()*+,;=@]+(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?|(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)+\/?))(\?[a-z0-9\-._~%!$&'()*+,;=:@\/?]*)?(#[a-z0-9\-._~%!$&'()*+,;=:@\/?]*)?$/im.test(subject)) {
    // Successful match
} else {
    // Match attempt failed
}

使用[Az]而不是[az]你的小az只匹配小写字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM