Match all entries { * } - javascript

I need to match all entries like { * } for string (using Javascript). How can I do it?
Here is an input: "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
thanks in advance

Using regular expression maybe:
var r = /{.*?}/g;
var s = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var matches = s.match(r);
Or if you want to strip those {} in results, you can run an .exec() loop to get a captured data only:
var r = /{(.*?)}/g;
var s = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var matches = [];
var match = null;
while(match = r.exec(s)) {
matches.push(match[1]);
}

You can try with the following regular expression:
var str = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n".
var m = str.match(/{.*?}/g);
You'll find all the matches inside m.
Further references: http://www.w3schools.com/jsref/jsref_match.asp

For just the text within the brackets, you should be able to use this pattern:
var pattern = new RegExp("([^{|^}]+)(?=})", "g");
var testString = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var bracketTextArray = testString.match(pattern);
The bracketTextArray variable will be an array that contains the following values:
"date", "time", "lat1", "lat2", "lon1", "lon2", "speed", "course", "height", "sats"
The regex matches every occurrence of one or more of any character except { and } (that's this part: ([^{|^}]+)), that are immediately followed by a } character (that's this part: (?=})). The "g" in the RegExp definition makes the pattern "greedy", so that it will find all occurrences.

Related

Get values from string through RegEx

I'm trying to get size values from a strings, which looks like:
https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/
I'm using match method and following RegEx:
'...'.match(/\/(\d+)x(\d+)\//g)
I hoped that the parentheses help to highlight the numbers:
But match returns only ["/80x90/"] without separate size values, like ["/80x90/", "80", "90"].
What am I'm doing wrong?
Here you can test my RegEx.
You don't need g modifier, without it you can get matching groups:
var url = 'https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/';
var res = url.match(/\/(\d+)x(\d+)\//);
console.log(res);
RegExp#exec will return all the captured group including the captured subexpression.
var url = 'https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/';
var patt = /\/(\d+)x(\d+)\//g;
var result = [];
while ((result = patt.exec(url)) !== null) {
console.log(result);
}

How to get all the matches matched the inner groups in RegEx .exec results

here is my code:
var regEx = /^abcd(\d)+efg$/i;
var data = "abcd1234efg";
var match = regEx.exec(data);
the result is:
["abcd1234efg","4"]
But what I want is every single number: 1,2,3,4, not only 4
how do i get it ?
add another example:
var regEx = /^abcd(xy|z)+efg$/i;
var data = "abcdxyzefg";
var match = regEx.exec(data);
what i want is ["abcdxyzefg","xy,"z"]. especially "xy" and "z"
thx~~
you need to put the quantifier, the +, inside the group:
^abcd(\d+)efg$
https://regex101.com/r/P6qQUq/1

match regular expression - JavaScript

So I have the following url:
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
I want to take username and token out of it;
I tried:
var match = (/#\{(.*?)\}/g.exec(oURL));
console.log(match);
but it is giving me:
["#{username}", "username", index: 27, input: "https://graph.facebook.com/#{username}/posts?access_token=#{token}"
Why isn't catching token?
Thanks
The problem is that exec only returns the first match from the given index whenever called.
Returns
If the match succeeds, the exec() method returns an array and updates
properties of the regular expression object. The returned array has
the matched text as the first item, and then one item for each
capturing parenthesis that matched containing the text that was
captured.
If the match fails, the exec() method returns null.
You would need to loop, continuously matching again to find all the matches.
var matches = [],
match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
matches.push(match)
}
console.log(matches)
However, if you are only interested in the first capture group, you can only add those to the matches array:
var matches = [],
match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
matches.push(match[1])
}
console.log(matches)
Try this instead:
oURL.match(/#\{(.*?)\}/g)
The answer you accepted is perfect, but I thought I'd also add that it's pretty easy to create a little helper function like this:
function getMatches(str, expr) {
var matches = [];
var match;
while (match = expr.exec(str)) {
matches.push(match[1]);
}
return matches;
}
Then you can use it a little more intuitively.
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
var expr = /#\{([^\{]*)?\}/g;
var result = getMatches(oURL, expr);
console.log(result);
http://codepen.io/Chevex/pen/VLyaeG
Try this:
var match = (/#\{(.*?)\}.*?#\{(.*?)\}/g.exec(oURL));

How to extract string in regex

I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo from the string.
Note: Input start can be any string and in place of number 2 it can be any number.
I would check if the [...] before the necessary [InvoiceNo] contains digits and is preceded with _ with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_ - Match underscore
\[\d+\] - Match [1234]-like substring
\s* - Optional spaces
\[([^\]]+)\] - The [some_invoice_123]-like substring
You can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1] below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
You could use something like so: \[([^[]+)\]$. This will extract the content within the last set of brackets. Example available here.
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);

Regex to grab strings between square brackets

I have the following string: pass[1][2011-08-21][total_passes]
How would I extract the items between the square brackets into an array? I tried
match(/\[(.*?)\]/);
var s = 'pass[1][2011-08-21][total_passes]';
var result = s.match(/\[(.*?)\]/);
console.log(result);
but this only returns [1].
Not sure how to do this.. Thanks in advance.
You are almost there, you just need a global match (note the /g flag):
match(/\[(.*?)\]/g);
Example: http://jsfiddle.net/kobi/Rbdj4/
If you want something that only captures the group (from MDN):
var s = "pass[1][2011-08-21][total_passes]";
var matches = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((match = pattern.exec(s)) != null)
{
matches.push(match[1]);
}
Example: http://jsfiddle.net/kobi/6a7XN/
Another option (which I usually prefer), is abusing the replace callback:
var matches = [];
s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);})
Example: http://jsfiddle.net/kobi/6CEzP/
var s = 'pass[1][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r ; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
example proving the edge case of unbalanced [];
var s = 'pass[1]]][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
add the global flag to your regex , and iterate the array returned .
match(/\[(.*?)\]/g)
I'm not sure if you can get this directly into an array. But the following code should work to find all occurences and then process them:
var string = "pass[1][2011-08-21][total_passes]";
var regex = /\[([^\]]*)\]/g;
while (match = regex.exec(string)) {
alert(match[1]);
}
Please note: i really think you need the character class [^\]] here. Otherwise in my test the expression would match the hole string because ] is also matches by .*.
'pass[1][2011-08-21][total_passes]'.match(/\[.+?\]/g); // ["[1]","[2011-08-21]","[total_passes]"]
Explanation
\[ # match the opening [
Note: \ before [ tells that do NOT consider as a grouping symbol.
.+? # Accept one or more character but NOT greedy
\] # match the closing ] and again do NOT consider as a grouping symbol
/g # do NOT stop after the first match. Do it for the whole input string.
You can play with other combinations of the regular expression
https://regex101.com/r/IYDkNi/1
[C#]
string str1 = " pass[1][2011-08-21][total_passes]";
string matching = #"\[(.*?)\]";
Regex reg = new Regex(matching);
MatchCollection matches = reg.Matches(str1);
you can use foreach for matched strings.

Categories