RegEx for Google Analytics that picks text within urls - regex

I am trying to build a RegEx that picks urls that end with "/topic". These urls have a different number of folders so whereas one might be www.example.com/pijamas/topic another could be www.example.com/pijamas/strippedpijamas/topic
What regular expression can I use to do that? My attempt is ^www.example.com/[a-zA-Z][1,]/topic$ but this hasn't worked. Even if it worked I'd like to have a shorter RegEx to do this really.
Any help on this would be much appreciated.
Thank you, A.

Try this:
^www\.example\.com\/[\w\/]*topic$

You need to make a few changes to your regex. Firstly, the dot (.) is a special character and needs to be escaped by prefacing it with a backslash.
Secondly, you probably meant {1,} instead of [1,] – the latter defines a character class. You can substitute {1,} with +.
Then there's the fact that your second URL has one more subdirectory, so you need to somehow incorporate a / into your regex.
Putting all this together:
^www\.example\.com/[a-zA-Z]+(/[a-zA-Z]+)*/topic$
To shorten it, you can use the i option to match regardless of case, cutting down the two [a-zA-Z] to [a-z]. Try this online here.

Related

Regex to find two words on the page

I'm trying to find all pages which contain words "text1" and "text2".
My regex:
text1(.|\n)*text2
it doesn't work..
If your IDE supports the s (single-line) flag (so the . character can match newlines), you can search for your items with:
(text1).*(text2)|\2.*\1
Example with s flag
If the IDE does not support the s flag, you will need to use [\s\S] in place of .:
(text1)[\s\S]*(text2)|\2[\s\S]*\1
Example with [\s\S]
Some languages use $1 and $2 in place of \1 and \2, so you may need to change that.
EDIT:
Alternately, if you want to simply match that a file contains both strings (but not actually select anything), you can utilize look-aheads:
(?s)^(?=.*?text1)(?=.*?text2)
This doesn't care about the order (or number) of the arguments, and for each additional text that you want to search for, you simply append another (?=.*?text_here). This approach is nice, since you can even include regex instead of just plain strings.
text0[\s\S]*text1
Try this.This should do it for you.
What this does is match all including multiline .similar to having .*? with s flag.
\s takes care of spaces,newlines,tabs
\S takes care any non space character.
If you want the regex to match over several lines I would try:
text1[\w\W]*text2
Using . is not a good choice, because it usually doesn't match over multiple lines. Also, for matching single characters I think using square brackets is more idiomatic than using ( ... | ... )
If you want the match to be order-independent then use this:
(?:text1[\w\W]*text2)|(?:text2[\w\W]*text1)
Adding a response for IntelliJ
Building on #OnlineCop's answer, to swap the order of two expressions in IntelliJ,you would style the search as in the accepted response, but since IntelliJ doesn't allow a one-line version, you have to put the replace statement in a separate field. Also, IntelliJ uses $ to identify expressions instead of \.
For example, I tend to put my nulls at the end of my comparisons, but some people prefer it otherwise. So, to keep things consistent at work, I used this regex pattern to swap the order of my comparisons:
Notice that IntelliJ shows in a tooltip what the result of the replacement will be.
For me works text1*{0,}(text2){0,}.
With {0,} you can decide to get your keyword zero or more times OR you set {1,x} to get your keyword 1 or x-times (how often you want).

Parsing valid parent directories with regex

Given the string a/b/c/d which represents a fully-qualified sub-directory I would like to generate a series of strings for each step up the parent tree, i.e. a/b/c, a/b and a.
With regex I can do a non-greedy /(.*?)\// which will give me matches of a, b and c or a greedy /(.*)\// which will give me a single match of a/b/c. Is there a way I can get the desired results specified above in a single regex or will it inherently be unable to create two matches which eat the same characters (if that makes sense)?
Please let me know if this question is answered elsewhere... I've looked, but found nothing.
Note this question is about whether it's possible with regex. I know there are many ways outside of regex.
One solution building on idea in this other question:
reverse the string to be matched: d/c/b/a For instance in PHP use strrev($string )
match with (?=(/(?:\w+(?:/|$))+))
This give you
/c/b/a
/b/a
/a
Then reverse the matches with strrev($string )
This give you
a/b/c/
a/b/
a/
If you had .NET not PCRE you could do matching right to left and proably come up with same.
Completely different answer without reversing string.
(?<=((?:\w+(?:/|$))+(?=\w)))
This matches
a/
a/b/
a/b/c/
but you have to use C# which use variable lookbehind
Yes, it's possible:
/([^\/]*)\//
So basically it replaces your .*? with [^/]*, and it does not have to be non-greedy. Since / is a special character in your case, you will have to escape it, like so: [^\/]*.

Simple regex for matching up to an optional character?

I'm sure this is a simple question for someone at ease with regular expressions:
I need to match everything up until the character #
I don't want the string following the # character, just the stuff before it, and the character itself should not be matched. This is the most important part, and what I'm mainly asking. As a second question, I would also like to know how to match the rest, after the # character. But not in the same expression, because I will need that in another context.
Here's an example string:
topics/install.xml#id_install
I want only topics/install.xml. And for the second question (separate expression) I want id_install
First expression:
^([^#]*)
Second expression:
#(.*)$
[a-zA-Z0-9]*[\#]
If your string contains any other special characters you need to add them into the first square bracket escaped.
I don't use C#, but i will assume that it uses pcre... if so,
"([^#]*)#.*"
with a call to 'match'. A call to 'search' does not need the trailing ".*"
The parens define the 'keep group'; the [^#] means any character that is not a '#'
You probably tried something like
"(.*)#.*"
and found that it fails when multiple '#' signs are present (keeping the leading '#'s)?
That is because ".*" is greedy, and will match as much as it can.
Your matcher should have a method that looks something like 'group(...)'. Most matchers
return the entire matched sequence as group(0), the first paren-matched group as group(1),
and so forth.
PCRE is so important i strongly encourage you to search for it on google, learn it, and always have it in your programming toolkit.
Use look ahead and look behind:
To get all characters up to, but not including the pound (#): .*?(?=\#)
To get all characters following, but not including the pound (#): (?<=\#).*
If you don't mind using groups, you can do it all in one shot:
(.*?)\#(.*) Your answers will be in group(1) and group(2). Notice the non-greedy construct, *?, which will attempt to match as little as possible instead of as much as possible.
If you want to allow for missing # section, use ([^\#]*)(?:\#(.*))?. It uses a non-collecting group to test the second half, and if it finds it, returns everything after the pound.
Honestly though, for you situation, it is probably easier to use the Split method provided in String.
More on lookahead and lookbehind
first:
/[^\#]*(?=\#)/ edit: is faster than /.*?(?=\#)/
second:
/(?<=\#).*/
For something like this in C# I would usually skip the regular expressions stuff altogether and do something like:
string[] split = exampleString.Split('#');
string firstString = split[0];
string secondString = split[1];

Regex href match a number

Well, here I am back at regex and my poor understanding of it. Spent more time learning it and this is what I came up with:
/(.*)
I basically want the number in this string:
510973
My regex is almost good? my original was:
"/<a href=\"travis.php?theTaco(.*)\">(.*)<\/a>/";
But sometimes it returned me huge strings. So, I just want to get numbers only.
I searched through other posts but there is such a large amount of unrelated material, please give an example, resource, or a link directing to a very related question.
Thank you.
Try using a HTML parser provided by the language you are using.
Reason why your first regex fails:
[0-9999999] is not what you think. It is same as [0-9] which matches one digit. To match a number you need [0-9]+. Also .* is greedy and will try to match as much as it can. You can use .*? to make it non-greedy. Since you are trying to match a number again, use [0-9]+ again instead of .*. Also if the two number you are capturing will be the same, you can just match the first and use a back reference \1 for 2nd one.
And there are a few regex meta-characters which you need to escape like ., ?.
Try:
<a href=\"travis\.php\?theTaco=([0-9]+)\">\1<\/a>
To capture a number, you don't use a range like [0-99999], you capture by digit. Something like [0-9]+ is more like what you want for that section. Also, escaping is important like codaddict said.
Others have already mentioned some issues regarding your regex, so I won't bother repeating them.
There are also issues regarding how you specified what it is you want. You can simply match via
/theTaco=(\d+)/
and take the first capturing group. You have not given us enough information to know whether this suits your needs.

Match last word after /

so, i have some kind of intern urls: for example "/img/pic/Image1.jpg" or "/pic/Image1.jpg" or just "Image1.jpg", and i need to match this "Image1.jpg" in other words i want to match last character sequence after / or if there are no / than just character sequence. Thank you in advance!
.*/(.*) won't work if there are no /s.
([^/]*)$ should work whether there are or aren't.
Actually you don't need regexp for this.
s="this/is/a/test"
s.substr(s.lastIndexOf("/")+1)
=> test
and it also works fine for strings without any / because then lastIndexOf returns -1.
s="hest"
s.substr(s.lastIndexOf("/")+1)
=> hest
.*/([^/]*)
The capturing group matches the last sequence after /.
The following expression would do the trick:
/([\w\d._-]*)$
Or even easier (but i think this has also been posted below before me)
([^/]+)$
A simple regex that I have tested:
\w+(.)\w+$
Here is a good site you can test it on: http://rubular.com/
In Ruby You would write
([^\/]*)$
Regexps in Ruby are quite universal and You can test them live here: http://rubular.com/
By the way: maybe there is other solution that not involves regexps? E.g File.basenam(path) (Ruby again)
Edit: profjim has posted it earlier.
I noticed you said in your comments you're using javascript. You don't actually need a regex for this and I always think it's nice to have an alternative to using regex.
var str = "/pic/Image1.jpg";
str.split("/").pop();
// example:
alert("/pic/Image1.jpg".split("/").pop()); // alerts "Image1.jpg"
alert("Image2.jpg".split("/").pop()); // alerts "Image2.jpg"
Something like .*/(.*)$ (details depend on whether we're talking about Perl, or some other dialect of regular expressions)
First .* matches everything (including slashes). Then there's one slash, then there's .* that matches everything from that slash to the end (that is $).
The * operates greedily from left to right, which means that when you have multiple slashes, the first .* will match all but the last one.