I'm having trouble trying to use multiple back references in a javascript match so far I've got: -
function newIlluminate() {
var string = "the time is a quarter to two";
var param = "time";
var re = new RegExp("(" + param + ")", "i");
var test = new RegExp("(time)(quarter)(the)", "i");
var matches = string.match(test);
$("#debug").text(matches[1]);
}
newIlluminate();
#Debug when matching the Regex 're' prints 'time' which is the value of param.
I've seen match examples where multiple back references are used by wrapping the match in parenthesis however my match for (time)(quarter)... is returning null.
Where am I going wrong? Any help would be greatly appreciated!
Your regex is literally looking for timequarterthe and splitting the match (if it finds one) into the three backreferences.
I think you mean this:
var test = /time|quarter|the/ig;
Your regex test simply doesn't match the string (as it does not contain the substring timequarterthe). I guess you want alternation:
var test = /time|quarter|the/ig; // does not even need a capturing group
var matches = string.match(test);
$("#debug").text(matches!=null ? matches.join(", ") : "did not match");
Related
I want a Javascript regex or with any possible solution,
For a given string finds all the substrings that start with a particular string and end with a particular character. The returned set of subStrings can be an Array.
this string can also have nested within parenthesis.
var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";
starting char = "myfunc" ending char = ")" . here ending character should be first matching closing paranthesis.
output: function with arguments.
[myfunc(1,2),
myfunc(3,4),
myfunc(5,6),
func(7,8)]
I have tried with this. but, its returning null always.
var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";
var re = /\myfunc.*?\)/ig
var match;
while ((match = re.exec(str)) != null){
console.log(match);
}
Can you help here?
I tested your regex and it seems to work fine:
let input = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))"
let pattern = /myfunc.*?\)/ig
// there is no need to use \m since it does nothing, and NO you dont need it even if you use 'm' at the beginning.
console.log(input.match(pattern))
//[ "myfunc(1,2)", "myfunc(3,4)", "myfunc(5,6)" ]
If you use (?:my|)func\(.+?\) you will be able to catch 'func(7,8)' too.
(?:my|)
( start of group
?: non capturing group
my| matches either 'my' or null, this will match either myfunc or func
) end of group
Test the regex here: https://regex101.com/r/3ujbdA/1
Hi all I tried to create some regex with random value.
var data = "demo purpose?"; **OR** var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp("\\b(" + data + ")\\b", "g");
console.log(sentence.match(re)); // output ["demo purpose"]
In variable data have two different value demo purpose? & demo purpose with only question mark. Both console out are same please any one Give me hint what should i do in these case.
-
Thank you
you need to escape ? (i.e. write \\?) or else it would be interpreted as a quantifier in regex.
Furthermore, the \\b is not really necessary because it tries to match a non blank char in which case there is nothing behind demo purpose? so sentence.match(new RegExp("\\b(demo purpose\\?)\\b", "g")) would return null.
If you want randomness, use Math.random. Make an array and get an random integer or 0 or 1 (with Math.floor) as the index.
In order to pass variables into JS regex when using constructor notation, you need to escape all characters that act as regex special characters (quantifiers, group delimiters, etc.).
The escape function is available at MDN Web site:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
Note also, that \b is a word boundary, and it prevents from matching the strings you need as ? is a non-word character. If you do not need to match word boundaries, remove \b. If you need to check if the search word is a whole word, use (?:^|\W) at the beginning and (?!\w) at the end and use exec rather than match to obtain access to the captured group 1.
So, your code will become:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var data = "demo purpose?";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp("(?:^|\\W)(" + escapeRegExp(data) + ")(?!\\w)", "g");
while ((m = re.exec(sentence)) !== null) {
console.log(m[1]); // output ["demo purpose?"]
}
If you search for emo purpose?, no result will be returned since there will be no match.
This
var data = "demo purpose?"; // **OR** var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp(/demo purpose\?/, "g");
console.log(sentence.match(re)); // output ["demo purpose?"]
return ["demo purpose?"],
changing RegExp("xxx", "g"); to RegExp(/xxx/, "g");
You can do
var data = /demo purpose\?/; // **OR** var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp(data, "g");
console.log(sentence.match(re));
and you will get the same output
I am trying to create a regular expression in JS which will match the occurences of box and return the full compound word
Using the string:
the box which is contained within a box-wrap has a box-button
I would like to get:
[box, box-wrap, box-button]
Is this possible to match these words only using the string box?
This is what I have tried so far but it does not return the results I desire.
http://jsfiddle.net/w860xdme/
var str ='the box which is contained within a box-wrap has a box-button';
var regex = new RegExp('([\w-]*box[\w-]*)', 'g');
document.getElementById('output').innerHTML=str.match(regex);
Try this way:
([\w-]*box[\w-]*)
Regex live here.
Requested by comments, here is a working example in javascript:
function my_search(word, sentence) {
var pattern = new RegExp("([\\w-]*" + word + "[\\w-]*)", "gi");
sentence.replace(pattern, function(match) {
document.write(match + "<br>"); // here you can do what do you want
return match;
});
};
var phrase = "the box which is contained within a box-wrap " +
"has a box-button. it is inbox...";
my_search("box", phrase);
Hope it helps.
I'll just throw this out there:
(box[\w-]*)+
You can use this regex in JS:
var w = "box"
var re = new RegExp("\\b" + w + "\\S*");
RegEx Demo
This should work, note the 'W' is upper case.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
\Wbox\W
It looks like you're wanting to use the match with a regex. Match is a string method that will take a regex as an argument and return an array containing matches.
var str = "your string that contains all of the words you're looking for";
var regex = /you(\S)*(?=\s)/g;
var returnedArray = str.match(regex);
//console.log(returnedArray) returns ['you', 'you\'re']
I'm trying to return the number of times a letter appears in a word.
I'm passing the letter to a function like so
function getCount(letter)
{
var pattern = '/' + letter + '/g';
var matches = word.match(pattern);
return matches.length;
}
Unfortunately matches is null so I'm unable to call length on it, I know the letter appears in the word as I've already checked that
word.indexOf(letter) > -1
I suspect the problem is with the way I'm building or evaluating pattern
Here's how you build a non literal regular expression :
var pattern = new RegExp(letter, 'g');
See the MDN on building a regular expression.
And here's a simpler solution to count the occurrences of the letter :
return word.split(letter).length-1;
You can do this:
function hasClass(letter) {
var pattern = new RegExp(letter,'g'); // Create a regular expression from the string
var matches = word.match(pattern);
return matches;
Ref: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp
This was also answered here: javascript new regexp from string
I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.