select the key and the value without the equal using regex - javascript

Hava a string like this:
"let key1=value1; let key2=value2;"
I want to select the key and value as groups using regex, I've tried using look around.
/(\w+)(?=\=)(\w+);/g
but it doesn't work with me, any suggestions?

The following regex should do the trick: (let (\w+) ?= ?(\w+);?)+.
Each let statement will be a match where the key will be the group 2 and the value the group 3.

The (?=\=) expression part is a lookahead, a zero-width assertion, it does not consume text but requires it to be present on the right. When you say (?=\=)(\w+) you want \w+ pattern to start matching on =. As \w does not match =, your regex always fails.
Use
/(\w+)=(\w+);/g
JavaScript (borrowed from How do you access the matched groups in a JavaScript regular expression?):
var myString = "let key1=value1; let key2=value2;";
var myRegexp = /(\w+)=(\w+);/g;
match = myRegexp.exec(myString);
while (match != null) {
console.log(match[1] + "," + match[2]);
match = myRegexp.exec(myString);
}

To be more specific, we could use (\w+) ?= ?(\w+);?+

Related

regex match not outputting the adjacent matches javascript

i was experimenting on regex in javascript. Then i came across an issue such that let consider string str = "+d+a+", I was trying to output those characters in the string which are surrounded by +, I used str.match(/\+[a-z]\+/ig), so here what I'm expecting is ["+d+","+a+"], but what i got is just ["+d+"], "+a+" is not showing in the output. Why?
.match(/.../g) returns all non-overlapping matches. Your regex requires a + sign on each side. Given your target string:
+d+a+
^^^
^^^
Your matches would have to overlap in the middle in order to return "+a+".
You can use look-ahead and a manual loop to find overlapping matches:
var str = "+d+a+";
var re = /(?=(\+[a-z]\+))/g;
var matches = [], m;
while (m = re.exec(str)) {
matches.push(m[1]);
re.lastIndex++;
}
console.log(matches);
With regex, when a character gets consumed with a match, then it won't count for the next match.
For example, a regex like /aba/g wouldn't find 2 aba's in a string like "ababa".
Because the second "a" was already consumed.
However, that can be overcome by using a positive lookahead (?=...).
Because lookaheads just check what's behind without actually consuming it.
So a regex like /(ab)(?=(a))/g would return 2 capture groups with 'ab' and 'a' for each 'aba'.
But in this case it just needs to be followed by 1 fixed character '+'.
So it can be simplified, because you don't really need capture groups for this one.
Example snippet:
var str = "+a+b+c+";
var matches = str.match(/\+[a-z]+(?=\+)/g).map(function(m){return m + '+'});
console.log(matches);

Match by regular expression to string replace by JavaScript

My string is like
5blog5sett5ings5[5slider5][5][5ima5ge5]
I like to match any digit into second brackets from end by regular expression.
For this case, my target digit is 5 into [5].
I like to select where before pattern like
5blog5sett5ings5[5slider5][ and after pattern like ][5ima5ge5]
I will use it for JavaScript string replace. Text can be different but the before and after patterns are like that. For better understanding see the image.
I tried something like
(?<=.+[.+?][)\d(?=][.+?])
but did not work.
I think you could just use a lookahead to check if there ] and one more [ ] ahead until end.
\d+(?=]\[[^\]]*]$)
See demo at regex101
(be aware that lookbehind you tried is not available in js regex)
I guess you can use:
\[(\d+)\][^\]]+]$
Regex Demo & Explanation
var myString = "5blog5sett5ings5[5slider5][5][5ima5ge5]";
var myRegexp = /\[(\d+)\][^\]]+]$/mg;
var match = myRegexp.exec(myString);
console.log(match[1]);
Use this:
^.*\[(\d*)\]\[[^\]]*\]$
Where:
^ is the begin of the string
.* means any character
\[ and \] matches literal squared brackets
(\d*) is what you want to match
[^\]]* is the content of the last couple of brackets
$ is the end of the string
See an example:
var str = "5blog5sett5ings5[5slider5][5][5ima5ge5]";
var res = str.match(/^.*\[(\d*)\]\[[^\]]*\]$/);
console.log(res[1])

Javascript regular expression between brackets

Let's say in the following text
I want [this]. I want [this too]. I don't want \[this]
I want the contents of anything between [] but not \[]. How would I go about doing that? So far I've got /\[([^\]]+)\]/gi. but it matched everything.
Use this one: /(?:^|[^\\])\[(.*?)\]/gi
Here's a working example: http://regexr.com/3clja
?: Non-capturing group
^|[^\\] Beggining of string or anything but \
\[(.*?)\] Match anything between []
Here's a snippet:
var string = "[this i want]I want [this]. I want [this too]. I don't want \\[no]";
var regex = /(?:^|[^\\])\[(.*?)\]/gi;
var match = null;
document.write(string + "<br/><br/><b>Matches</b>:<br/> ");
while(match = regex.exec(string)){
document.write(match[1] + "<br/>");
}
Use this regexp, which first matches the \[] version (but doesn't capture it, thereby "throwing it away"), then the [] cases, capturing what's inside:
var r = /\\\[.*?\]|\[(.*?)\]/g;
^^^^^^^^^ MATCH \[this]
^^^^^^^^^ MATCH [this]
Loop with exec to get all the matches:
while(match = r.exec(str)){
console.log(match[1]);
}
/(?:[^\\]|^)\[([^\]]*)/g
The content is in the first capture group, $1
(?:^|[^\\]) matches the beginning of a line or anything that's not a slash, non-capturing.
\[ matches a open bracket.
([^\]]*) captures any number of consecutive characters that are not closed brackets
\] matches a closing bracket

RegEx that will match the last occurrence of dot in a string

I have a filename that can have multiple dots in it and could end with any extension:
tro.lo.lo.lo.lo.lo.png
I need to use a regex to replace the last occurrence of the dot with another string like #2x and then the dot again (very much like a retina image filename) i.e.:
tro.lo.png -> tro.lo#2x.png
Here's what I have so far but it won't match anything...
str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " #2x.");
any suggestions?
You do not need a regex for this. String.lastIndexOf will do.
var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
str = str.substr(0, i) + "#2x" + str.substr(i);
}
See it in action.
Update: A regex solution, just for the fun of it:
str = str.replace(/\.(?=[^.]*$)/, "#2x.");
Matches a literal dot and then asserts ((?=) is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.
Just use special replacement pattern $1 in the replacement string:
console.log("tro.lo.lo.lo.lo.lo.png".replace(/\.([^.]+)$/, "#2x.$1"));
// "tro.lo.lo.lo.lo.lo#2x.png"
You can use the expression \.([^.]*?):
str.replace(/\.([^.]*?)$/, "#2x.$1");
You need to reference the $1 subgroup to copy the portion back into the resulting string.
working demo http://jsfiddle.net/AbDyh/1/
code
var str = 'tro.lo.lo.lo.lo.lo.zip',
replacement = '#2x.';
str = str.replace(/.([^.]*)$/, replacement + '$1');
$('.test').html(str);
alert(str);​
To match all characters from the beginning of the string until (and including) the last occurence of a character use:
^.*\.(?=[^.]*$) To match the last occurrence of the "." character
^.*_(?=[^.]*$) To match the last occurrence of the "_" character
Use \. to match a dot. The character . matches any character.
Therefore str.replace(/\.([^\.]*)$/, ' #2x.').
You could simply do like this,
> "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1#2x");
'tro.lo.lo.lo.lo.lo#2xzip'
Why not simply split the string and add said suffix to the second to last entry:
var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.');
arr[arr.length-2] += '#2x';
var newString = arr.join('.');
'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.#x2$2")

Javascript regular expression matching prior and trailing characters

I have this string in a object:
<FLD>dsfgsdfgdsfg;NEW-7db5-32a8-c907-82cd82206788</FLD><FLD>dsfgsdfgsd;NEW-480e-e87c-75dc-d70cd731c664</FLD><FLD>dfsgsdfgdfsgfd;NEW-0aad-440a-629c-3e8f7eda4632</FLD>
this.model.get('value_long').match(/[<FLD>\w+;](NEW[-|\d|\w]+)[</FLD>]/g)
Returns:
[";NEW-7db5-32a8-c907-82cd82206788<", ";NEW-480e-e87c-75dc-d70cd731c664<", ";NEW-0aad-440a-629c-3e8f7eda4632<"]
What is wrong with my regular expression that it is picking up the preceding ; and trailing <
here is a link to the regex
http://regexr.com?30k3m
Updated:
this is what I would like returned:
["NEW-7db5-32a8-c907-82cd82206788", "NEW-480e-e87c-75dc-d70cd731c664", "NEW-0aad-440a-629c-3e8f7eda4632"]
here is a JSfiddle for it
http://jsfiddle.net/mwagner72/HHMLK/
Square brackets create a character class, which you do not want here, try changing your regex to the following:
<FLD>\w+;(NEW[-\d\w]+)</FLD>
Since it looks like you want to grab the capture group from each match, you can use the following code to construct an array with the capture group in it:
var regex = /<FLD>\w+;(NEW[\-\d\w]+)<\/FLD>/g;
var match = regex.exec(string);
var matches = [];
while (match !== null) {
matches.push(match[1]);
match = regex.exec(string);
}
[<FLD>\w+;] would match one of the characters inside of the square brackets, when I think what you actually want to do is match all of those. Also for the other character class, [-|\d|\w], you can remove the | because it is already implied in a character class, | should only be used for alternation inside of a group.
Here is an updated link with the new regex: http://jsfiddle.net/RTkzx/1

Categories

Resources