Regex for hostname - javascript

I have the following code (currHost is hostname):
if (currHost.match(/(alpha|beta|test|dev|load|local)\./))
but I need to add additional conditions such as
file:
.od*. (* is wildcard)
dev-wa.
.sq*. (* is wildcard)
.hbox.
Example MATCHING URLS:
file://c:blahblahblah
www.sqc.mydomain.com
www.sqa.mydomain.com
www.odd.mydomain.com
www.odp.mydomain.com
www.hbox.mydomain.com
dev-wa.mydomain.com
Example NOT MATCHING URLS:
www.sqcmydomain.com
www.sqamydomain.com
www.oddmydomain.com
www.odp.mydomain.com
www.hboxx.mydomain.com
dev-waa.mydomain.com
not sure how to approach this?
Thanks!

For your file matches you can simply use
document.location.protocol == 'file:'
and the expression you're looking for is
curHost.match(/(alpha|beta|test|dev|load|local|\.od.*|dev-wa|\.sq.*|\.hbox)\./)
Just remember that this expression will also match www.od.mydomain.com and oddmydomain.com since it's a valid match too. If you don't want this, you need to either specify a full expression (with the .com part) or specify the number of characters after the od/sq part. For example
curHost.match(/(alpha|beta|test|dev|load|local|\.od.{1}|dev-wa|\.sq.{1}|\.hbox)\./)
For one letter match.
If you want to specifically match those string only in the beginning of the domain, with or without www. you can use
curHost.match(/^(www\.)?(alpha|beta|test|dev|load|local|od.+|dev-wa|sq.+|hbox)\./)

if (currHost.match(/(alpha|beta|test|dev|load|local|file:|dev-wa|od\*|hbox)?\./))
Just add like above? Or do you mean something else?. I've added the a slash in from of the asterix. Added a questionmark at the end to make it ungreedy

Related

Regex for specific strings/paths

I need a regular expression to match many specific paths/strings but I can't figure it out.
E.g.
../foo/hoo/something.js -> Needs to match ../foo/hoo/
../foo/bar/somethingElse.js -> Needs to match ../foo/bar/
../foo/something-else.js -> Needs to match ../foo/
What I tried with no luck is the following regex:
/\..\/foo\/|bar\/|hoo\//g
This should work out for you:
/(\.\.\/foo\/(hoo\/|bar\/)?)/
https://regex101.com/r/1aTf7y/1
So you select ../foo/ at first and then have a group that can either contain hoo/ or bar/. And the question mark allows 0 or one instances.
If you want to be a little less specific, you could also do
/(\.\.\/[^\/]+\/(hoo\/|bar\/)?)/
The [^\/]+ allows all characters except for a slash
You can use the regex
(\/[^\/\s]+)+(?=\/)
see the regex101 demo
function match(str){
console.log(str.match(/(\/[^\/\s]+)+(?=\/)/)[0]);
}
match('./foo/hoo/something.js');
match('../foo/bar/somethingElse.js');
match('../foo/something-else.js');
This should be the regex for matching all dirs without filename.
/^(.*[/])[^/]+$/

Finding difficulty in correct regex for URL validation

I have to set some rules on not accepting wrong url for my project. I am using regex for this.
My Url is "http ://some/resource/location".
This url should not allow space in beginning or middle or in end.
For example these spaces are invalid:
"https ://some/(space here in middle) resource/location"
"https ://some/resource/location (space in end)"
"(space in starting) https ://some/resource/location"
"https ://(space here) some/resource/location"
Also these scenario's are invalid.
"httpshttp ://some/resource/location"
"https ://some/resource/location,https ://some/resource/location"
Currently I am using a regex
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
This regex accepts all those invalid scenarios. I am unable to find the correct matching regex which will accept only if the url is valid. Can anyone help me out on this?
We need to validate n number of scenarios for URL validation. If your particular about your given pattern then above regex expression from other answer looks good.
Or
If you want to take care of all the URL validation scenarios please refer In search of the perfect URL validation regex
/(ftp|http|https){1}:\/\/(?:.(?! ))+$/
is this regex OK ?
use this
^\?([\w-]+(=[\w-]*)?(&[\w-]+(=[\w-]*)?)*)?$
See live demo
This considers each "pair" as a key followed by an optional value (which maybe blank), and has a first pair, followed by an optional & then another pair,and the whole expression (except for the leading?) is optional. Doing it this way prevents matching ?&abc=def
Also note that hyphen doesn't need escaping when last in the character class, allowing a slight simplification.
You seem to want to allow hyphens anywhere in keys or values. If keys need to be hyphen free:
^\?(\w+(=[\w-]*)?(&\w+(=[\w-]*)?)*)?$

Regexp javascript - url match with localhost

I'm trying to find a simple regexp for url validation, but not very good in regexing..
Currently I have such regexp: (/^https?:\/\/\w/).test(url)
So it's allowing to validate urls as http://localhost:8080 etc.
What I want to do is NOT to validate urls if they have some long special characters at the end like: http://dodo....... or http://dododo&&&&&
Could you help me?
How about this?
/^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?(\/[.\w]*)*$/
Will match: http://domain.com:port/path or just http://domain or http://domain:port
/^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?$/
match URLs without path
Some explanations of regex blocks:
Domain: \w+(\.\w+)* to match text with dots: localhost or www.yahoo.com (could be as long as Path or Port section begins)
Port: (:[0-9]+)? to match or to not match a number starting with semicolon: :8000 (and it could be only one)
Path: \/?(\/[.\w]*)* to match any alphanums with slashes and dots: /user/images/0001.jpg (until the end of the line)
(path is very interesting part, now I did it to allow lone or adjacent dots, i.e. such expressions could be possible: /. or /./ or /.../ and etc. If you'd like to have dots in path like in domain section - without border or adjacent dots, then use \/?(\/\w+(.\w+)*)* regexp, similar to domain part.)
* UPDATED *
Also, if you would like to have (it is valid) - characters in your URL (or any other), you should simply expand character class for "URL text matching", i.e. \w+ should become [\-\w]+ and so on.
If you want to match ABCD then you may leave the start part..
For Example to match http://localhost:8080
' just write
/(localhost).
if you want to match specific thing then please focus the term that you want to search, not the starting and ending of sentence.
Regular expression is for searching the terms, until we have a rigid rule for the same. :)
i hope this will do..
It depends on how complex you need the Regex to be. A simple way would be to just accept words (and the port/domain):
^https?:\/\/\w+(:[0-9]*)?(\.\w+)?$
Remember you need to use the + character to match one or more characters.
Of course, there are far better & more complicated solutions out there.
^https?:\/\/localhost:[0-9]{1,5}\/([-a-zA-Z0-9()#:%_\+.~#?&\/=]*)
match:
https://localhost:65535/file-upload-svc/files/app?query=abc#next
not match:
https://localhost:775535/file-upload-svc/files/app?query=abc#next
explanation
it can only be used for localhost
it also check the value for port number since it should be less than 65535 but you probably need to add additional logic
You can use this. This will allow localhost and live domain as well.
^https?:\/\/\w+(\.\w+)*(:[0-9]+)?(\/.*)?$
I'm pretty late to the party but now you should consider validating your URL with the URL class. Avoid the headache of regex and rely on standard
let isValid;
try {
new URL(endpoint); // Will throw if URL is invalid
isValid = true;
} catch (err) {
isValid = false;
}
^https?:\/\/(localhost:([0-9]+\.)+[a-zA-Z0-9]{1,6})?$
Will match the following cases :
http://localhost:3100/api
http://localhost:3100/1
http://localhost:3100/AP
http://localhost:310
Will NOT match the following cases :
http://localhost:3100/
http://localhost:
http://localhost
http://localhost:31

How to identify all URLs that contain a (domain) substring?

If I am correct, the following code will only match a URL that is exactly as presented.
However, what would it look like if you wanted to identify subdomains as well as urls that contain various different query strings - in other words, any address that contains this domain:
var url = /test.com/
if (window.location.href.match(url)){
alert("match!");
}
If you want this regex to match "test.com" you need to escape the "." and both of the "/" that means any character in regex syntax.
Escaped : \/test\.com\/
Take a look for here for more info
No, your pattern will actually match on all strings containing test.com.
The regular expresssion /test.com/ says to match for test[ANY CHARACTER]com anywhere in the string
Better to use example.com for example links. So I replaces test with example.
Some example matches could be
http://example.com
http://examplexcom.xyz
http://example!com.xyz
http://example.com?q=123
http://sub.example.com
http://fooexample.com
http://example.com/asdf/123
http://stackoverflow.com/?site=example.com
I think you need to use /g. /g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one:
var /test.com/g;
If you want to test if an URL is valid this is the one I use. Fairly complex, because it takes care also of numeric domain & a few other peculiarities :
var urlMatcher = /(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?#)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/;
Takes care of parameters and anchors etc... dont ask me to explain the details pls.

Regex to match part of a string

Regex fun again...
Take for example http://something.com/en/page
I want to test for an exact match on /en/ including the forward slashes, otherwise it could match 'en' from other parts of the string.
I'm sure this is easy, for someone other than me!
EDIT:
I'm using it for a string.match() in javascript
Well it really depends on what programming language will be executing the regex, but the actual regex is simply
/en/
For .Net the following code works properly:
string url = "http://something.com/en/page";
bool MatchFound = Regex.Match(url, "/en/").Success;
Here is the JavaScript version:
var url = 'http://something.com/en/page';
if (url.match(/\/en\//)) {
alert('match found');
}
else {
alert('no match');
}
DUH
Thank you to Welbog and Chris Ballance to making what should have been the most obvious point. This does not require Regular Expressions to solve. It simply is a contains statement. Regex should only be used where it is needed and that should have been my first consideration and not the last.
If you're trying to match /en/ specifically, you don't need a regular expression at all. Just use your language's equivalent of contains to test for that substring.
If you're trying to match any two-letter part of the URL between two slashes, you need an expression like this:
/../
If you want to capture the two-letter code, enclose the periods in parentheses:
/(..)/
Depending on your language, you may need to escape the slashes:
\/..\/
\/(..)\/
And if you want to make sure you match letters instead of any character (including numbers and symbols), you might want to use an expression like this instead:
/[a-z]{2}/
Which will be recognized by most regex variations.
Again, you can escape the slashes and add a capturing group this way:
\/([a-z]{2})\/
And if you don't need to escape them:
/([a-z]{2})/
This expression will match any string in the form /xy/ where x and y are letters. So it will match /en/, /fr/, /de/, etc.
In JavaScript, you'll need the escaped version: \/([a-z]{2})\/.
You may need to escape the forward-slashes...
/\/en\//
Any reason /en/ would not work?
/\/en\// or perhaps /http\w*:\/\/[^\/]*\/en\//
You don't need a regex for this:
location.pathname.substr(0, 4) === "/en/"
Of course, if you insist on using a regex, use this:
/^\/en\//.test(location.pathname)

Categories