Javascript Regex: Exclude all other except one possibility - javascript

I want few validations like (for my url):
cars : valid
cars/ : valid
(Any number of '/' after cars are valid)
cars- : invalid
cars* : invalid
carsp : invalid
(Any other character after cars except '/' is invalid)
**cars/new: valid
cars/old: valid
(Once we get '/' we can have anything).**
What should be regex for this:
I tried with:
cars[/]*[^-]
Its not working.

^cars(\/.*)?$
^...$ String should start with, and end with (Or simply, the string should only contain).
cars cars
(...)? and possibly
\/.* a forward slash followed by any character.

It looks like you want "cars" followed by either
nothing
or anything starting by at least one /
So this would be
cars(\/.*)?
But the real problem here is determining what you really need. Some context might help.

Use a positive look-ahead assertion:
/^cars(?=\/).*/
If there is a slash right after 'cars' word than it considers the rest part of the string

Related

What Regex would capture both the beginning and end from of a string?

I am trying to edit a DateTime string in typescript file.
The string in question is 02T13:18:43.000Z.
I want to trim the first three characters including the letter T from the beginning of a string AND also all 5 characters from the end of the string, that is Z000., including the dot character. Essentialy I want the result to look like this: 13:18:43.
From what I found the following pattern (^(.*?)T) can accomplish only the first part of the trim I require, that leaves the initial result like this: 13:18:43.000Z.
What kind of Regex pattern must I use to include the second part of the trim I have mentioned? I have tried to include the following block in the same pattern (Z000.)$ but of course it failed.
Thanks.
Any help would be appreciated.
There is no need to use regular expression in order to achieve that. You can simply use:
let value = '02T13:18:43.000Z';
let newValue = value.slice(3, -5);
console.log(newValue);
it will return 13:18:43, assumming that your string will always have the same pattern. According to the documentation slice method will substring from beginIndex to endIndex. endIndex is optional.
as I see you only need regex solution so does this pattern work?
(\d{2}:)+\d{2} or simply \d{2}:\d{2}:\d{2}
it searches much times for digit-digit-doubleDot combos and digit-digit-doubleDot at the end
the only disadvange is that it doesn't check whether say there are no minutes>59 and etc.
The main reason why I didn't include checking just because I kept in mind that you get your dates from sources where data that are stored are already valid, ex. database.
Solution
This should suffice to remove both the prefix from beginning to T and postfix from . to end:
/^.*T|\..*$/g
console.log(new Date().toISOString().replace(/^.*T|\..*$/g, ''))
See the visualization on debuggex
Explanation
The section ^.*T removes all characters up to and including the last encountered T in the string.
The section \..*$ removes all characters from the first encountered . to the end of the string.
The | in between coupled with the global g flag allows the regular expression to match both sections in the string, allowing .replace(..., '') to trim both simultaneously.

Dot at start and end using regex

Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in
/^[^\.].*[^\.]$/;
But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."
How about
/^(?!\.)[^\.]*\.?[^\.]*(?!\.).$/
The correct regex for
my requirement is that I can have at most one dot ('.') in the string
and that can't be at the start and end
is
/^([^\.]|([^\.]*.?[^\.]))$/
/^([^\.]|([^\.].*[^\.]))$/ or /^[^\.].*[^\.]$/ accepts String
containing more than 1 dot . Hence it will also accept X..X too.
Please check working snippet also
validateString("XX.X");
validateString("X.X");
validateString("X...X");
validateString("X");
validateString("X.X.X");
validateString(".XX");
validateString("XX.");
function validateString(str){
console.log(/^([^\.]|([^\.]*.?[^\.]))$/.test(str));
}
With your current regex, you are targeting a string that should be at least 2 characters long, as both [^\.] parts are a mandatory character.
Your regex should include an extra check in case there is just one character, which you can do like this:
^([^\.]|([^\.]+\.?[^\.]+))$

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-]*)?)*)?$

javascript regexp to match path depth

Been struggling for the last hour to try and get this regexp to work but cannot seem to crack it.
It must be a regexp and I cannot use split etc as it is part of a bigger regexp that searches for numerous other strings using .test().
(public\/css.*[!\/]?)
public/css/somefile.css
public/css/somepath/somefile.css
public/css/somepath/anotherpath/somefile.css
Here I am trying to look for path starting with public/css followed by any character except for another forward slash.
so "public/css/somefile.css" should match but the other 2 should not.
A better solution may be to somehow specify the number of levels to match after the prefix using something like
(public\/css\/{1,2}.*)
but I can't seem to figure that out either, some help with this would be appreciated.
edit
No idea why this question has been marked down twice, I have clearly stated the requirement with sample code and test cases and also attempted to solve the issue, why is it being marked down ?
You can use this regex:
/^(public\/css\/[^\/]*?)$/gm
^ : Starts with
[^/] : Not /
*?: Any Characters
$: Ends with
g: Global Flag
m: Multi-line Flag
Something like this?
/public\/css\/[^\/]+$/
This will match
public/css/[Any characters except for /]$
$ is matching the end of the string in regex.

Javascript regex to find a base URL

I'm going mad with this regex in JS:
var patt1=/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i;
If I give an input string like "http://www.eitb.com/servicios/concursos/516522/" this regex it's supossed to return NULL, because there are a "folder" after base URL. It works in PHP, but not in Javascript, like in this script:
<script type="text/javascript">
var str="http://www.eitb.com/servicios/concursos/516522/";
var patt1=/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i;
document.write(str.match(patt1));
</script>
It returns
http://www.eitb.com/servicios/concursos/516522/,,/516522,,/
The question is: why it is not working? How to make it work?
The idea is to implement this regex in another function to get NULL when the URL passed is not in the correct format:
http://www.eitb.com/ -> Correct
http://www.eitb.com/something -> Incorrect
Thanks
I'm no javascript pro, but accustomed to perl regexp, so I'll give it a try; the . in the middle of the regexp might need to be escaped, as it can map a / and jinx the whole regexp.
Try this way:
var patt1=/^http(s)?:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i;
Considering you have a properly formatted URL this simple RegExp should do the trick every time.
var patt1=/^https?:\/\/[^\/]+/i;
Here's the breakdown...
Starting with the first position (denoted by ^)
Look for http
http can be followed by s (denoted by the ? which means 0 or 1 of the character or set before it)
Then look for :// after the http or https (denoted by :\/\/)
Next match any number of characters except for / (denoted by [^\/]+ - the + means 1 or more)
Case insensitive (denoted by i)
NOTE: this will also pick up ports http://example.com:80 - to get rid of the :80 (or a colon followed by any port number) simply add a : to the negated character class [^\/:] for example.

Categories