Javascript Regex doesn't match with my String - javascript

I have the following String :
var resultLine= "[UT] - GSM incoming call : STEP 1 - Simulate reception from server (1)Rerun3713 msAssertion ok"
And the following code which is responsible to check of the String matched with the Regex :
var resultRE = /^([ \w-]*: )?(.+) \((\d+), (\d+), (\d+)\)Rerun/;
var resultMatch = resultLine.match(resultRE);
if (resultMatch) {
return true;
} else {
return false;
}
In this case, i have an error in my Regex because i always get "false".
Where is my mistake ?

I would recommend the following pattern based on what it appears you are looking for:
var resultRE = /^([\[ \w\]-]*: )(.+) \(([0-9, ]*)\)Rerun(.*)$/
This should force all capture groups to exist, even if they are empty, and will allow for multiple numbers before Rerun as you seem to expect.

This matches nothing in your string
([ \w-]*: )?
Since it was optional, that doesn't matter because it gets caught by the all inclusive
(.+)
If you were trying to match the [UT] part with it's separator, it would look something like this
(\[\w+\][\s\-]*)?
As noted in the comments, you only have one number in parentheses but your regex requires three sets of them, separated by commas. This will allow any number of numbers, separated by commas indefinitely (I don't know if there's a limit or not).
\((\d+,\s)*(\d+)\)
If you need something more specific, you'll have to be more specific about what template your matching, not a specific case. But the best I can figure with what you've provided is
^(\[\w\][\s\-]*)?(.+)\((\d+,\w)*(\d+)\)Rerun

var resultRE = /\((\d+)(?:, (\d+))?(?:, (\d+))?\)Rerun/;
if (resultRE.test(resultLine)) {
var num1 = RegExp.$1,
num2 = RegExp.$2,
num3 = RegExp.$3;
}

Related

Regex to validate URL hash not working in Javascript

I have the following code for checking the URL hash part and extract the query strings.
var getCleanHash = function(){
return (/^[a-z-_&=\d]*$/.test(location.hash.substr(1))) ? location.hash.substr(1) : "";
}
so the regex used here is /^[a-z-_&=\d]*$/, but if I have the query strings like type=mytype&q=search, it is returning empty value. If I remove the ^ from the regex, it starts returning the query strings. But then it will not perform any checks as intended in regex. I suppose ^ denotes the first character, but not entirely sure why it doesn't match with my query string part.
Can someone help me to find what this Regex actually means and how can I fix the issue with empty query strings?
var getCleanHash = function(){
return (/^[a-z\d\-_&\=]*$/.test(location.hash.substring(1))) ? location.hash.substring(1) : "";
}
I think you should use .substring(1) instead of .substr(1)
[a-z\d-_&=]* means you are testing:
for any hash even empty ones on the entire length(from start ^ to end $)
a to z and digits plus the following characters(-_&=)

JavaScript: How to find and retrieve numbers from a string

I'm using RPG Maker MV which is a game creator that uses JavaScript to create plugins. I have a plugin in JavaScript already, however I'm trying to edit a part of the plugin so that it basically checks if a certain string exists in a character in the game and if it does, then sets specific variables to numbers within that string.
for (var i = 0; i < page.list.length; i++) {
if (page.list[i].code == 108 && page.list[i].parameters[0].contains("<post:" + (n) + "," + (n) + ">")) {
var post = page.list[i].parameters[0];
var array = post.split(',');
this._origMovement.x = Number(array[1]);
this._origMovement.y = Number(array[1]);
break;
};
};
So I know the first 2 lines work and contains works when I only put a specific string. However I can't figure out how to check for 2 numbers that are separated by a comma and wrapped in '<>' tags, without knowing what the numbers would be.
Then it needs to extract those numbers and assign one to this._origMovement.x and the other to this._origMovement.y.
Any help would be greatly appreciated.
This is one of those rare cases where I'd use a regular expression. If you haven't come across regular expressions before I suggest reading an introduction to them, such as this one: https://regexone.com/
In your case, you probable want something like this:
var myRegex = /<post:(\d+),(\d+)>/;
var matches = myParameter.match(myRegex);
this._origMovement.x = matches[1]; //the first number
this._origMovement.y = matches[2]; //the second number
The myRegex variable is a regular expression that looks for the pattern you describe, and has 2 capture groups which look for a string of one or more digits (\d+ means "one or more digits"). The result of the .match() call gives you an array containing the entire match and the results of the capture groups.
If you want to allow for decimal numbers, you'll need to use a different capture group that allows for a decimal point, such as ([\d\.]+), which means "a sequence of one or more digits and decimal points", or more sophisticated, (\d+\.?\d*), which is "a sequence of one or more digits, following by an optional decimal point, followed by zero or more digits).
There are lots of good tutorials around to help you write good regular expressions, and sites that will help you live-test your expressions to make sure they work correctly. They're a powerful tool, but be careful not to over-use them!
Got it to work. For anyone who may ever be interested, the code is below.
for (var i = 0; i < page.list.length; i++) {
if (page.list[i].code == 108 && page.list[i].parameters[0].contains("<post:")) {
var myRegex = /<post:(\d+),(\d+)>/;
var matches = page.list[i].parameters[0].match(myRegex);
this._origMovement.x = matches[1]; //the first number
this._origMovement.y = matches[2]; //the second number
break;
}
};

JS: Check string if it is failing for some rules

Issue
Using regex to verify if a string is matching specific rules.
My Problem
My regexes seems not to bee valid and I don't know how to check a string for multiple regexes.
Example string
This is just a senseless string with less then 1.000,00 words. and 1 x abbrevations e.g. this one ( and so on).
Rules
Every sentence must begin with an upper case character or a number
There must not be a space between number and `x`
Never multiple spaces
There must not be spaces at the beginning and at the end of bracket content
My regex attempts
/([.?!])\s*(?= [A-Z0-9])/g // Sentence have to start with upper case
/([0-9]*)(x)/g // No space between number and 'x'
/\s{2,}/g // Two or more spaces
// don't know how to do last rule
if (/([.?!])\s*(?= [A-Z0-9])/.test(string); )
failing.push('capitalizeSentence');
else if ...
But maybe it can by done a bit more dynamic...
Expected result
I need to know which rules are not matching the string if there is any. So I would suggest an array with values for those rules failed.
So in this example string the result could be an array like this, as every rule is failing.
failing = [ 'capitalizeSentence', 'spaceNumber', 'multipleSpaces', 'spaceBrackets' ];
Something like this:
var rules = {
'capitalizeSentence': /[.?!]\s+[^A-Z\d]/,
'spaceNumber': /\d\s+x/,
'multipleSpaces': /\s\s/,
'spaceBrackets': /\(\s|\s\)/
}
var check = function(str){
return Object.keys(rules).reduce(function(results,key){
if(rules[key].test(str)) {
results.push(key);
}
return results;
},[]);
};
console.log(check('This is just a senseless string with less then 1.000,00 words. and 1 x abbrevations e.g. this one ( and so on).'));
Operates by checking for rules violations and adding those violation names to an array which is returned.

Does a string contain a price?

I'd like to check whether or not a string such as "The computer costs $2,000" contains a price or not.
I slightly modified this regex to fit my needs and the current regex that I am using looks like this:
var regexTest = /(?=.)^\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/;
If I do regexTest.test("$2,000"); it will return true. However, if I add additional characters to the string such as regexTest.test("The computer costs $2,000"); it will return false.
How should I modify the regex code in order to return true for the second example?
remove your ^ in regex. try this one
Also I recommend to remove $ as well so price like this $5.000,00 words will return true
var regexTest = /(?=.)\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?/;
console.log(regexTest.test('computer $5,000.00'));
console.log(regexTest.test('$5,000.00'));
console.log(regexTest.test('$5,000.00 that was computer price'));
console.log(regexTest.test('computer 5,000.00'));
The global modifier should work. Add the g after the last /
var regexTest = /(?=.)^\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/g;
Should match with all instances inside the test string.

Get id from url

I have the following example url: #/reports/12/expense/11.
I need to get the id just after the reports -> 12. What I am asking here is the most suitable way to do this. I can search for reports in the url and get the content just after that ... but what if in some moment I decide to change the url, I will have to change my algorythm.
What do You think is the best way here. Some code examples will be also very helpfull.
It's hard to write code that is future-proof since it's hard to predict the crazy things we might do in the future!
However, if we assume that the id will always be the string of consecutive digits in the URL then you could simply look for that:
function getReportId(url) {
var match = url.match(/\d+/);
return (match) ? Number(match[0]) : null;
}
getReportId('#/reports/12/expense/11'); // => 12
getReportId('/some/new/url/report/12'); // => 12
You should use a regular expression to find the number inside the string. Passing the regular expression to the string's .match() method will return an array containing the matches based on the regular expression. In this case, the item of the returned array that you're interested in will be at the index of 1, assuming that the number will always be after reports/:
var text = "#/reports/12/expense/11";
var id = text.match(/reports\/(\d+)/);
alert(id[1]);
\d+ here means that you're looking for at least one number followed by zero to an infinite amount of numbers.
var text = "#/reports/12/expense/11";
var id = text.match("#/[a-zA-Z]*/([0-9]*)/[a-zA-Z]*/")
console.log(id[1])
Regex explanation:
#/ matches the characters #/ literally
[a-zA-Z]* - matches a word
/ matches the character / literally
1st Capturing group - ([0-9]*) - this matches a number.
[a-zA-Z]* - matches a word
/ matches the character / literally
Regular expressions can be tricky (add expensive). So usually if you can efficiently do the same thing without them you should. Looking at your URL format you would probably want to put at least a few constraints on it otherwise the problem will be very complex. For instance, you probably want to assume the value will always appear directly after the key so in your sample report=12 and expense=11, but report and expense could be switched (ex. expense/11/report/12) and you would get the same result.
I would just use string split:
var parts = url.split("/");
for(var i = 0; i < parts.length; i++) {
if(parts[i] === "report"){
this.reportValue = parts[i+1];
i+=2;
}
if(parts[i] === "expense"){
this.expenseValue = parts[i+1];
i+=2;
}
}
So this way your key/value parts can appear anywhere in the array
Note: you will also want to check that i+1 is in the range of the parts array. But that would just make this sample code ugly and it is pretty easy to add in. Depending on what values you are expecting (or not expecting) you might also want to check that values are numbers using isNaN

Categories