I want to capture the value for name from query string with regular expression; I have done the folowing:
/name=(.*)/g
example: ?name=foo&bar=baz
But this grabs all string to the end; I know ^ is used for not; but I could not figure out the right syntax.
Thanks
If you want to use regex you can use a non greedy operator like this:
name=(.*?)&
Btw, you can also you another regex like this to cover more cases:
name=(.*?)(?:&|$)
Working demo
Javascript code:
var re = /name=(.*?)(?:&|$)/gm;
var str = 'example: ?name=foo&bar=baz\nexample: ?name=foo\nexample: ?bar=baz&name=foo';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
You can try /name=([^&]+)/ if you only have one or use global modifier for more
Related
I would like to have a match with
[testing]
but not
![testing]
This is my query to grab a string surrounded by square brackets:
\[([^\]]+)\]
var match = /^[^!]*\[([^\]]+)\]/.exec(issueBody);
if (match)
{
$ISSUE_BODY.selectRange(match.index, match.index+match[0].length);
}
and it works marvelously.
However, I have spent a good half hour on http://regexr.com/ trying to skip strings with a "!" in front, and couldn't.
EDIT: I'm sorry guys I didn't realize that there were operations that could not be supported by specific interpreters. I am writing in Javascript and apparently lookbehind is not supported, I get this error:
Uncaught SyntaxError: Invalid regular expression:
/(?
Sorry for wasting time :\
You can use alternation:
(?:^|[^!])(\[[^\]]+\])
RegEx Demo
Here (?:^|[^!]) will match start of input OR any character that is NOT !
Code:
var re = /(?:^|[^!])(\[[^\]]+\])/gm;
var str = '![foobar123]\n[xyz789]';
while ((m = re.exec(str)) !== null)
console.log(m[1]);
Output:
[xyz789]
In Javascript, where lookbehinds are not supported, you can use:
^[^!]*\[([^\]]+)\]
(with the multiline flag to match every start of a line)
See it on regexr.com.
And here's a visualization from debuggex.com:
You can just use capturing:
var re = /(?:^|[^!])(\[[^[\]]*])/g;
var str = '[goodtesting] ![badtesting] ';
var m;
while ((m = re.exec(str)) !== null) {
document.getElementById("r").innerHTML += m[1] + "<br/>";
}
<div id="r"/>
The (?:^|[^!])(\[[^[\]]*]) regex matches the start of string or any character other than a ! (with a non-capturing group (?:^|[^!])) and matches and captures the substring enclosed with [ and ] that has no [ and ] inside (with (\[[^[\]]*])). When we need to get multiple matches, we need to use RegExp#exec() and access the captured groups using the indices (here, index 1).
Also, in JS, when you do not need to check what is after the match, just a lookbehind without a lookahead, you can use a reverse string technique (use a lookahead with the reversed string):
function revStr(s) {
return s.split('').reverse().join('');
}
var re = /][^[\]]*\[(?!!)/g; // Here, the regex pattern is reverse, too
var str = '![badtesting] [goodtesting]';
var m;
while ((m = re.exec(revStr(str))) !== null) { // We reverse a string here
document.getElementById("res").innerHTML += revStr(m[0]); // and the matched value here
}
<div id="res"/>
This is not possible with longer patterns but this one seems simple enough to go for it.
I have a regular expression like this which extract the content between 2 characters and in this case its between 2 #'s
(?<=\#)(.*?)(?=\#)
and um using it as follows
var extract = str.match(/(?<=\#)(.*?)(?=\#)/).pop();
but the regex gives errors since I think I need to escape it. How do I correctly apply escape characters for the above regex?
Regex may be overkill for this task.
var result = str.split("#")[1] || "";
If there is no # in the string, result is the empty string.
If there is only one # in the string, result is everything after it.
If there are two or more # in the string, result is the substring between the first and second #.
#(.*?)#
or
#([^#]+)#
Simply use this and grab the group 1.See demo.
https://regex101.com/r/uE3cC4/14
var re = /#(.*?)#/gm;
var str = 'bazbarfoo#asad#';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Given this text:
1/12/2011
I did something.
10/5/2013
I did something else.
Here is another line.
And another.
5/17/2014
Lalala.
More text on another line.
I would like to use regex (or maybe some other means?) to get this:
["1/12/2011", "I did something.", "10/5/2013", "I did something else.\n\nHere is another line.\n\nAnd another.", "5/17/2014", "Lalala.\nMore text on another line."]
The date part and content part are each separate entries, alternating.
I've tried using [^] instead of the dot since JS's .* does not match new lines (as Matching multiline Patterns says), but then the match is greedy and takes up too much, so the resulting array only has 1 entry:
var split_pattern = /\b(\d\d?\/\d\d?\/\d\d\d\d)\n([^]+)/gm;
var array_of_mems = contents.match(split_pattern);
// => ["1/12/2011↵I did something else..."]
If I add a question mark to get [^]+?, which according to How to make Regular expression into non-greedy? makes the match non-greedy, then I only get the first character of the content part.
What's the best method? Thanks in advance.
(\d{1,2}\/\d{1,2}\/\d{4})\n|((?:(?!\n*\d{1,2}\/\d{1,2}\/\d{4})[\s\S])+)
You can try this.grab the captures.See demo.
https://regex101.com/r/sJ9gM7/126
var re = /(\d{1,2}\/\d{1,2}\/\d{4})\n|((?:(?!\n*\d{1,2}\/\d{1,2}\/\d{4})[\s\S])+)/gim;
var str = '1/12/2011\nI did something.\n\n10/5/2013\nI did something else.\n\nHere is another line.\n\nAnd another.\n\n5/17/2014\nLalala.\nMore text on another line.';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
You can use the exec() method in a loop to get your desired results.
var re = /^([\d/]+)\s*((?:(?!\s*^[\d/]+)[\S\s])+)/gm,
matches = [];
while (m = re.exec(str)) {
matches.push(m[1]);
matches.push(m[2]);
}
Output
[ '1/12/2011',
'I did something.',
'10/5/2013',
'I did something else.\n\nHere is another line.\n\nAnd another.',
'5/17/2014',
'Lalala.\nMore text on another line.' ]
eval.in
I have the following regexp
(?<=\.)\S+$
used to extract the extension (whatever comes after the last dot) of a string. regex101.com seems to accept my regexp: the string extension is correctly matched. As soon as I move it into a javascript script and try to test it against a string I get this error:
Invalid regular expression: /(?<=\.)\S+$/: Invalid group
I get the same error also with regex101 auto generated code:
var re = /(?<=\.)\S+$/;
var str = 'test.txt';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
see fiddle HERE
Any hint?
You cannot use look-behinds in JavaScript regex. There are some JavaScript look-behind workarounds, but they all have their own handicaps. To play it safe, use capturing groups. Here, the contents you need will be in the 2nd group:
(\.)([^.]+)$
Or, with just 1 capturing group (to increase performance):
\.([^.]+)$
Code:
var re = /\.([^.]+)$/;
var str = 'test.txt';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
alert(m[1]);
}
Due to babel-loader error
Replace var re = /(?<=\.)\S+$/; with var re = new RegExp("(?<=\\.)\\S+$");
I've searched for an example, but I'm so bad at Regular Expressions that I really need an answer to my specific example.
I'm using JavaScript and have the following string as an example:
accountActivityStatus.transactionHistorys.0.activityAmt
I need to be able to match that any given string starts with accountActivityStatus and contains a number somewhere after that.
Any assistance would be greatly appreciated:
^accountActivityStatus(?=.*\d).*$
Try this.See demo.
http://regex101.com/r/yZ7qJ6/7
var re = /^accountActivityStatus(?=.*\d).*$/gm;
var str = 'accountActivityStatus.transactionHistorys.0.activityAmt\naccountActivityStatus.transactionHistorys..activityAmt\naccountActivityStatus.transactionHistorys.4.activityAmt';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}