JavaScript regex to capture everything after the second to last backslash - javascript

I have a regex that looks like the following currently:
/^.*[\\\/]/
This will strip every single backslash from a string. The problem I'm facing is I have to now be able to capture everything from the second to last backslash.
Example:
/Users/foo/a/b/c would return b/c
/Another/example/ would return Another/Example
So I need to capture everything after the second to last backslash. How would the regex above do that?

Try with this simple solution:
s = "aaaa/bbbb/cccc/dddd";
s.split("/").slice(-2).join("/"); /* It will return "cccc/dddd" */

I assume that you mean forward slash, not backslash.
Here is a regex alternative to pierlauro's answer.
/([^\/]+\/[^\/]+)\/?$/
Regex101

As pierlauro's answer shows, split, join, and slice are probably the best options for this. But if you MUST use a regex (not sure why), you could employ something like the following:
\/?(\[^\/\]+?\/\[^\/\]+)\/?$
This regex accommodates for optional trailing slashes and for urls shorter than 2 /s. It leverages the $ character to focus our search scope on the end of the string.

Related

regex validating if string ends with specific set of words [duplicate]

I'm creating a javascript regex to match queries in a search engine string. I am having a problem with alternation. I have the following regex:
.*baidu.com.*[/?].*wd{1}=
I want to be able to match strings that have the string 'word' or 'qw' in addition to 'wd', but everything I try is unsuccessful. I thought I would be able to do something like the following:
.*baidu.com.*[/?].*[wd|word|qw]{1}=
but it does not seem to work.
replace [wd|word|qw] with (wd|word|qw) or (?:wd|word|qw).
[] denotes character sets, () denotes logical groupings.
Your expression:
.*baidu.com.*[/?].*[wd|word|qw]{1}=
does need a few changes, including [wd|word|qw] to (wd|word|qw) and getting rid of the redundant {1}, like so:
.*baidu.com.*[/?].*(wd|word|qw)=
But you also need to understand that the first part of your expression (.*baidu.com.*[/?].*) will match baidu.com hello what spelling/handle????????? or hbaidu-com/ or even something like lkas----jhdf lkja$##!3hdsfbaidugcomlaksjhdf.[($?lakshf, because the dot (.) matches any character except newlines... to match a literal dot, you have to escape it with a backslash (like \.)
There are several approaches you could take to match things in a URL, but we could help you more if you tell us what you are trying to do or accomplish - perhaps regex is not the best solution or (EDIT) only part of the best solution?

Find character pattern using regex

I am trying to find all occurrences of a special character / surrounded by either letters or numbers.
After many tries, I have come up with the following Regex that almost does what I need:
(?![a-z0-9])\/(?=[a-z0-9])
This works fine for these examples:
aa/aa
123/123
aa/123
However, it fails if there are two forward slashes together:
http://regexr.com/
In this case, it matches the second forward slash after http which I do not want.
How can I modify this Regex to meet my needs?
EDIT: I do not want to a match when two forward slashes are together. I only want to match if a single forward slash is surrounded by alphanumeric characters.
you would need a positive lookbehind group, like so:
(?<=[a-z0-9])+\/{1}(?=[a-z0-9]+)
however, according to http://regexr.com/ it is not supported in javascript.
Works fine in e.g. python http://pythex.org/
Easy!
(?![a-z0-9])\/+(?=[a-z0-9])
You should have put + for 1 on more occurrence of a character. So you should have written \/+ instead of just \/.
Try this
(!?[a-z0-9])\/(?=[a-z0-9])
Try this
[a-z0-9](\/)[a-z0-9]
Regex demo
Explanation:
( … ): Capturing group sample
\: Escapes a special character sample

Unable to find a string matching a regex pattern

While trying to submit a form a javascript regex validation always proves to be false for a string.
Regex:- ^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w].*))+(.jpeg|.JPEG|.jpg|.JPG)$
I have tried following strings against it
abc.jpg,
abc:.jpg,
a:.jpg,
a:asdas.jpg,
What string could possible match this regex ?
This regex won't match against anything because of that $? in the middle of the string.
Apparently using the optional modifier ? on the end string symbol $ is not correct (if you paste it on https://regex101.com/ it will give you an error indeed). If the javascript parser ignores the error and keeps the regex as it is this still means you are going to match an end string in the middle of a string which is supposed to continue.
Unescaped it was supposed to match a \$ (dollar symbol) but as it is written it won't work.
If you want your string to be accepted at any cost you can probably use Firebug or a similar developer tool and edit the string inside the javascript code (this, assuming there's no server side check too and assuming it's not wrong aswell). If you ignore the $? then a matching string will be \\\\w\\\\ww.jpg (but since the . is unescaped even \\\\w\\\\ww%jpg is a match)
Of course, I wrote this answer assuming the escaping is indeed the one you showed in the question. If you need to find a matching pattern for the correctly escaped one ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(\.jpeg|\.JPEG|\.jpg|\.JPG)$ then you can use this tool to find one http://fent.github.io/randexp.js/ (though it will find weird matches). A matching pattern is c:\zz.jpg
If you are just looking for a regular expression to match what you got there, go ahead and test this out:
(\w+:?\w*\.[jpe?gJPE?G]+,)
That should match exactly what you are looking for. Remove the optional comma at the end if you feel like it, of course.
If you remove escape level, the actual regex is
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpeg|.JPEG|.jpg|.JPG)$
After ^start the first pipe (([a-zA-Z]:)|(\\{2}\w+)\$?) which matches an alpha followed by a colon or two backslashes followed by one or more word characters, followed by an optional literal $. There is some needless parenthesis used inside.
The second part (\\(\w[\w].*))+ matches a backslash, followed by two word characters \w[\w] which looks weird because it's equivalent to \w\w (don't need a character class for second \w). Followed by any amount of any character. This whole thing one or more times.
In the last part (.jpeg|.JPEG|.jpg|.JPG) one probably forgot to escape the dot for matching a literal. \. should be used. This part can be reduced to \.(JPE?G|jpe?g).
It would match something like
A:\12anything.JPEG
\\1$\anything.jpg
Play with it at regex101. A better readable could be
^([a-zA-Z]:|\\{2}\w+\$?)(\\\w{2}.*)+\.(jpe?g|JPE?G)$
Also read the explanation on regex101 to understand any pattern, it's helpful!

Javascript regular Expressions cut off last parameters between slashes

Hi I'm new to regex and can't find a proper solution for this:
I want to cut off the last parameters of the url between the two slashes "/1032/" form url "http://www.blablabla.com/test.php/addpage/1032/"
That i have just http://www.blablabla.com/test.php/addpage/ ...though this part is not important of being matched...so just cut off the parameters between the last slashes...
What i did was:
curr_url= "http://www.blablabla.com/test.php/addpage/1032/";
expression =/.*\/./;
alert(expression.exec(curr_url));
Result is "http://www.blablabla.com/test.php/addpage/1"
Now i could cut off the last parameter by a slice but thats not reasonable i guess
Any better solutions? Thanks a lot!
curr_url.match(/.+(\/.+\/)$/)
["http://www.blablabla.com/test.php/addpage/1032/", "/1032/"]
First greedy .+ captures everything to last slash and then backs off to next-to-last, because rest of pattern would fail otherwise. () capture everything between this slash and last an then \/$ at the end tell that string should end after last slash. Move slashes outside brackets if you only want number itself.
It seems though I misinterpreted your intent. If you need first part of string, you can use regexp suggested bellow with a little change:
curr_url.match(/(.+)\/.+/)[1]
It captures "everything until slash, and then some more". It will first reach last slash in string, but then back off to previous slash, because there's not "then some more", thus leaving exactly the part of string you want.
var parts=curr_url.split('/');
After that you can get any part from the array.
In your expression
/.*\/./
you need the last dot to tell the pattern that there is a character after the slash following, but this is also matched and therefore in your result. If you remove it it will match till the last slash, so no solution.
But there is a way to define what should be after the pattern and to not match that stuff. Its called a look ahead assertion.
So you could do
/.*\/(?!$)/
and (?!$) is a negative lookahead assertion that means "Match the previous slash only if the end of the string (the $) is not following".
curr_url= "http://www.blablabla.com/test.php/addpage/1032/";
expression =/.*\/(?!$)/;
alert(expression.exec(curr_url));
Would return also what you want.

Regex for number surrounded by slashes

Like the title says, I have a (faulty) Regex in JavaScript, that should check for a "2" character (in this case) surrounded by slashes. So if the URL was http://localhost/page/2/ the Regex would pass.
In my case I have something like http://localhost/?page=2 and the Regex still passes.
I'm not sure why. Could anyone tell me what's wrong with it?
/^(.*?)\b2\b(.*?$)/
(I'm going to tell you, I didn't write this code and I have no idea how it works, cause I'm really bad with Regex)
Seems too simple but shouldn't this work?:
/\/2\//
http://jsfiddle.net/QHac8/1/
As it's javascript you have to escape the forward slashes as they are the delimiters for a regex string.
or if you want to match any number:
/\/\d+\//
You don't check for a digit surrounded by slashes. The slashes you see are only your regex delimiters. You check for a 2 with a word boundary \b on each side. This is true for /2/ but also for =2
If you want to allow only a 2 surrounded by slashes try this
/^(.*?)\/2\/(.*?)$/
^ means match from the start of the string
$ match till the end of the string
(.*?) those parts are matching everything before and after your 2 and those parts are stored in capturing groups.
If you don't need those parts, then Richard D is right and the regex /\/2\// is fine for you.

Categories

Resources