Regex to match path like /^String1(anything)(String2 or String3)/ - javascript

For example:
String1: Books>Programming>
String2: Databases>
String3: Languages>
Anything: ''
is matched by the following regex:
/^Books>Programming>(Databases>|Languages>)/
Now, let's say Anything is not empty, e.g. "whatever1>", how should the regex change?
I tried with lookaround but no luck, I may be missing something obvious.

If I got you corectly you want to match path like Books>Programming>[anything]>(Databases> | Languages>). If so you can do it like this.
let String1 = "Books>Programming>",
String2 = "Databases>",
String3 = "Languages>"
let regex = new RegExp(`${String1}(.*?)>(?:${String2}|${String3})`)
Benefit of this method is that you can modify variables at will and create modified regex while executing your code so it's not hard-coded.
Now if you want to test if string matches this pattern you can use:
regex.test("Books>Programming>whatever1>Databases>")
And if you want to extrat whatever1 from this just use:
"Books>Programming>abc>Databases>".match(regex)[1]

You can use String.prototype.split to acheive that without the use of regular expressions. Like this:
function getParts(str) {
var parts = str.split(">"); // split the string by ">"
if(!parts[parts.length - 1].length) // if the last part is empty
parts.pop(); // remove it
return parts; // return the array of the parts (ordered by default)
}
console.log(getParts("Something>Books>Another thing>Programming>"));

Related

Regex - Match a string between second occurance of characters

I have a string of text that looks something like this:
?q=search&something=that&this=example/
In that example, I need to grab that . I'm using the following regex below:
var re = new RegExp("\&(.*?)\&");
Which going re[1] is giving me:
something=that - but it needs to be only that
I tried:
var re = new RegExp("\=(.*?)\&");
But that gives me everything from the first equals sign, so:
search&something=that
Is the output when it just needs to be:
that
I need to somehow target the second occurrences of 2 characters and grab whats in between them. How best do I go about this?
You can use
/something=([^&]+)/
and take the first group, see the JavaScript example:
let url = '?q=search&something=that&this=example/';
let regex = /something=([^&]+)/
let match = regex.exec(url);
console.log(match[1]);
split seems more suited to your case:
"?q=search&something=that&this=example/".split("&")[1].split("=")[1]
Then you could also implement a simple method to extract any wanted value :
function getValue(query, index) {
const obj = query.split("&")[index];
if(obj) obj.split("=")[1]
}
getValue("?q=search&something=that&this=example/", 1);

How can I inverse matched result of the pattern?

Here is my string:
Organization 2
info#something.org.au more#something.com market#gmail.com single#noidea.com
Organization 3
headmistress#money.com head#skull.com
Also this is my pattern:
/^.*?#[^ ]+|^.*$/gm
As you see in the demo, the pattern matches this:
Organization 2
info#something.org.au
Organization 3
headmistress#money.com
My question: How can I make it inverse? I mean I want to match this:
more#something.com market#gmail.com single#noidea.com
head#skull.com
How can I do that? Actually I can write a new (and completely different) pattern to grab expected result, but I want to know, Is "inverting the result of a pattern" possible?
No, I don't believe there is a way to directly inverse a Regular Expression but keeping it the same otherwise.
However, you could achieve something close to what you're after by using your existing RegExp to replace its matches with an empty string:
var everythingThatDidntMatchStr = str.replace(/^.*?#[^ ]+|^.*$/gm, '');
You can replace the matches from first RegExp by using Array.prototype.forEach() to replace matched RegExp with empty string using `String.ptototype.replace();
var re = str.match(/^.*?#[^ ]+|^.*$/gm);
var res = str;
re.forEach(val => res = res.replace(new RegExp(val), ""));

How do I make a regular expression that matches everything on a line after a given character?

If I have a String in JavaScript
key=value
How do I make a RegEx that matches key excluding =?
In other words:
var regex = //Regular Expression goes here
regex.exec("key=value")[0]//Should be "key"
How do I make a RegEx that matches value excluding =?
I am using this code to define a language for the Prism syntax highlighter so I do not control the JavaScript code doing the Regular Expression matching nor can I use split.
Well, you could do this:
/^[^=]*/ // anything not containing = at the start of a line
/[^=]*$/ // anything not containing = at the end of a line
It might be better to look into Prism's lookbehind property, and use something like this:
{
'pattern': /(=).*$/,
'lookbehind': true
}
According to the documentation this would cause the = character not to be part of the token this pattern matches.
use this regex (^.+?)=(.+?$)
group 1 contain key
group 2 contain value
but split is better solution
.*=(.*)
This will match anything after =
(.*)=.*
This will match anything before =
Look into greedy vs ungreedy quantifiers if you expect more than one = character.
Edit: as OP has clarified they're using javascript:
var str = "key=value";
var n=str.match(/(.*)=/i)[1]; // before =
var n=str.match(/=(.*)/i)[1]; // after =
var regex = /^[^=]*/;
regex.exec("key=value");

javascript, regex parse string content in curly brackets

i am new to regex. I am trying to parse all contents inside curly brackets in a string. I looked up this post as a reference and did exactly as one of the answers suggest, however the result is unexpected.
Here is what i did
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/
regex.exec(abc) // i got ["{string1}", "string1"]
//where i am expecting ["string1", "string2"]
i think i am missing something, what am i doing wrong?
update
i was able to get it with /g for a global search
var regex = /{(.*?)}/g
abc.match(regex) //gives ["{string1}", "{string2}"]
how can i get the string w/o brackets?
"test/abcd{string1}test{string2}test".match(/[^{}]+(?=\})/g)
produces
["string1", "string2"]
It assumes that every } has a corresponding { before it and {...} sections do not nest. It will also not capture the content of empty {} sections.
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g
var matches;
while(matches = regex.exec(abc))
console.log(matches);
Try this:
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g //g flag so the regex is global
abc.match(regex) //find every match
a good place to read about Regex in javascript is here, and a nice place to test is here
good luck!
Nothing wrong. But you'll need to look at your capturing groups (the second element in the array) to get the content you wanted (you can ignore the first). To get all occurences, it's not enough to run exec once, you'll need to loop over the results using match.
Edit: nevermind that, afaik you can't access capturing groups with match. A simpler solution would be using a positive lookahead, as Mike Samuel suggested.
This result:
["{string1}", "string1"]
is showing you that for the first match, the entire regex matched "{string1}" and the first capturing parentheses matched "string1".
If you want to get all matches and see all capturing parens of each match, you can use the "g" flag and loop through, calling exec() multiple times like this:
var abc = "test/abcd{string1}test{string2}test"; //any string
var regex = /{(.+?)}/g;
var match, results = [];
while (match = regex.exec(abc)) {
results.push(match[1]); // save first captured parens sub-match into results array
}
// results == ["string1", "string2"]
You can see it work here: http://jsfiddle.net/jfriend00/sapfm/
try this for file
const fs = require('fs');
fs.readFile('logs.txt', function(err, data) {
if(err) throw err;
const paragraph = "'" + data + "'";
const regex = /\d+\<;>\S+\<;>(\d+)\<;/g;
const found = paragraph.match(regex);
console.log(found);
})

Can regex matches in javascript match any word after an equal operator?

I am trying to target ?state=wildcard in this statement :
?state=uncompleted&dancing=yes
I would like to target the entire line ?state=uncomplete, but also allow it to find whatever word would be after the = operator. So uncomplete could also be completed, unscheduled, or what have you.
A caveat I am having is granted I could target the wildcard before the ampersand, but what if there is no ampersand and the param state is by itself?
Try this regular expression:
var regex = /\?state=([^&]+)/;
var match = '?state=uncompleted&dancing=yes'.match(regex);
match; // => ["?state=uncompleted", "uncompleted"]
It will match every character after the string "\?state=" except an ampersand, all the way to the end of the string, if necessary.
Alternative regex: /\?state=(.+?)(?:&|$)/
It will match everything up to the first & char or the end of the string
IMHO, you don't need regex here. As we all know, regexes tend to be slow, especially when using look aheads. Why not do something like this:
var URI = '?state=done&user=ME'.split('&');
var passedVals = [];
This gives us ['?state=done','user=ME'], now just do a for loop:
for (var i=0;i<URI.length;i++)
{
passedVals.push(URI[i].split('=')[1]);
}
Passed Vals wil contain whatever you need. The added benefit of this is that you can parse a request into an Object:
var URI = 'state=done&user=ME'.split('&');
var urlObjects ={};
for (var i=0;i<URI.length;i++)
{
urlObjects[URI[i].split('=')[0]] = URI[i].split('=')[1];
}
I left out the '?' at the start of the string, because a simple .replace('?','') can fix that easily...
You can match as many characters that are not a &. If there aren't any &s at all, that will of course also work:
/(\?state=[^&]+)/.exec("?state=uncompleted");
/(\?state=[^&]+)/.exec("?state=uncompleted&a=1");
// both: ["?state=uncompleted", "?state=uncompleted"]

Categories