简体   繁体   中英

Regular Expression Failure javascript

Is there any reason the following string should fail the regular expression below?

String: "http://devices/"

Expression:

/^(http:\/\/|https:\/\/|ftp:\/\/|www.|pop:\/\/|imap:\/\/){1}([0-9A-Za-z]+\.)/.test(input.val())

Thank you for your consideration.

Yes it will fail because of the last dot . in your regular expression.

/^  ...  \.)/
         ^^

There is not one in the string you are validating against.

http://devices 
              ^ Should be a dot, not a forward slash

Live Demo

If you are planning on using regex to do this, I would probably prefer using a RegExp Object to avoid all the escaping, or group the prefixes together using a non-capturing group.

/^((?:https?|ftp|pop|imap):\/{2}|www\.)  ...  $/

The last character in the string must be a period. see "\\." at the end of the regex.

You can use http://rubular.com/ to test simple regex expressions and what their matches are.

The reason why it's failing is because, you are using:

^(http:\/\/|https:\/\/|ftp:\/\/|www.|pop:\/\/|imap:\/\/){1}([0-9A-Za-z]+\.)

and you should use:

^(http:\/\/|https:\/\/|ftp:\/\/|www.|pop:\/\/|imap:\/\/){1}([0-9A-Za-z]+.)
                                     You don't have to escape . --------^

You need to close the regex with a $ .

On this two last: .) , this dot should be optional, as it is needed to validade.

to satisfy this "http://devices/" the regex in java at least is:

^((http://)|(https://)|(ftp://)|(pop://)|(imap://)){1}(www.)?([0-9A-Za-z]+)(.)?([0-9A-Za-z]+)?$

Are those / at the beggining and the end code delimiters?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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