Currently, I am trying to implement string interpolation for my language.
The string interpolation looks something like this:
let x = " Baby"
let message = "Hello $(x)"
My current regex to capture interpolated expression is:
const regex = /[$][(].*?[)]/g;
However, the regex above works well with non-bracketed expressions, but it does not work properly when the interpolated expression have brackets, for example:
let message = "My number is $(square(1+2))"
// the captured group would be `$(square(1+2)` , which is missing a bracket
I could not use greedy quantifiers. If not it will not work when there is more than one interpolated expression, such as:
let message = "My number is $(x) $(y) $(z)"
// if capture greedily, it would be `$(x) $(y) $(z)`, which is not desired
How do I greedily capture interpolated expressions based on situations?
Note: I'm looking for answer in JavaScript.
You can use template string (or literal string) like this
let x = 1, y = 2, z = 3;
console.log(`Mu number ${x} ${y} ${z}`);
Updated regex what you created, this will allow you to capture the second bracket it is there. Please find the following regex, btw I am not able to understand the third scenario. Test this regex and let me know if it fulfills your reqt. If not then elaborate on the third scenario and I will update my regex.
For scenario 3:
'[$][(].*?[\)]+' will capture '$(x)' '$(y)' '$(z)' differently. Mean to say match individually.
'[$][(].*[\)]+' will capture '$(x) $(y) $(z)' as one string. Whole string.
Please let me know if it works.
Related
Given an pattern by a user, such as [h][a-z][gho], and a string "gkfhxhk" I'm trying to see if the string contains the pattern.
The pattern means that the first letter would be 'h', the next letter can be any letter from a-z, and the 3rd letter can be either 'g' or 'h' or 'o'. This is supposed to work for any pattern. So another pattern could be [y][b-f][jm].
First I tried to use nested for loops to create a list of all possible strings but that didn't work. Then I tried using RegExp where I pass in the pattern but I'm not quite sure if I'm approaching that the right way:
let string = "gkfhxhk";
// pattern [h][a-z][gho]
let re = new RegExp('ha-zg|h');
let result = re.match(re);
This just returns a null in the result. Any ideas on how to do this?
This is exactly the type of problem regex was designed to solve. Your syntax is just wrong. This site is an excellent resource for learning regex. As for this specific example, the pattern you want is h[a-z][gho]. (The form [h][a-z][gho] works as well, but the brackets around h are unnecessary.) And in JavaScript, a regex pattern is a special literal, written with // instead of "".
var re = /h[a-z][gho]/;
var str1 = "gkfhxhk";
var str2 = "gkajflh";
console.log(str1.match(re));
console.log(str2.match(re));
Note that match returns a list of matches, not a simple true/false value. It returns null when there are no matches.
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), ""));
I am trying to replace a string with two fractions "x={2x-21}/{x+12}+{x+3}/{x-5}" with a string
"x=\frac{2x-21}{x+12}+\frac{x+3}{x-5}" (i.e. convert from jqMath to LaTex).
To achieve this, I've written the following code:
var initValue = "(\{.*\}(?=\/))\/(\{.*\})";
var newValue = "\\frac$1$2";
var re = new RegExp (initValue,"g");
var resultString = givenString.replace(re,newValue);
return resultString;
This code seems to work for strings with just one fraction (e.g. "x={2x-21}/{x+12}") but when I try to apply it to the example with two fractions, the result is x=\frac{2x-21}/{x+12}+{x+3}{x-5}. As far as I understand, regex engine captures {2x-21}/{x+12}+{x+3} as the first group and {x-5} as the second group. Is there any way to get the result that I want with regular expressions?
The same question is applicable to other patterns with several non-nested delimiters, for example: "I like coffee (except latte) and tea (including mint tea)". Is it possible to capture both statements in parentheses?
If not, I will probably have to write a function for this (which is ok, but I wanted to make sure this is the right approach).
({[^}]+})\/({[^}]+})
Try this.See demo.Repalce by \\frac$1$2.
http://regex101.com/r/tF5fT5/24
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");
I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");