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.
Related
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;
}
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
I'm getting nowhere with this...
I need to test a string if it contains %2 and at the same time does not contain /. I can't get it to work using regex. Here is what I have:
var re = new RegExp(/.([^\/]|(%2))*/g);
var s = "somePotentially%2encodedStringwhichMayContain/slashes";
console.log(re.test(s)) // true
Question:
How can I write a regex that checks a string if it contains %2 while not containing any / slashes?
While the link referred to by Sebastian S. is correct, there's an easier way to do this as you only need to check if a single character is not in the string.
/^[^\/]*%2[^\/]*$/
EDIT: Too late... Oh well :P
Try the following:
^(?!.*/).*%2
either use inverse matching as shown here: Regular expression to match a line that doesn't contain a word?
or use indexOf(char) in an if statement. indexOf returns the position of a string or char in a string. If not found, it will return -1:
var s = "test/";
if(s.indexOf("/")!=-1){
//contains "/"
}else {
//doesn't contain "/"
}
I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.
I'm trying to execute a search of sorts (using JavaScript) on a list of strings. Each string in the list has multiple words.
A search query may also include multiple words, but the ordering of the words should not matter.
For example, on the string "This is a random string", the query "trin and is" should match. However, these terms cannot overlap. For example, "random random" as a query on the same string should not match.
I'm going to be sorting the results based on relevance, but I should have no problem doing that myself, I just can't figure out how to build up the regular expression(s). Any ideas?
The query trin and is becomes the following regular expression:
/trin.*(?:and.*is|is.*and)|and.*(?:trin.*is|is.*trin)|is.*(?:trin.*and|and.*trin)/
In other words, don't use regular expressions for this.
It probably isn't a good idea to do this with just a regular expression. A (pure, computer science) regular expression "can't count". The only "memory" it has at any point is the state of the DFA. To match multiple words in any order without repeat you'd need on the order of 2^n states. So probably a really horrible regex.
(Aside: I mention "pure, computer science" regular expressions because most implementations are actually an extension, and let you do things that are non-regular. I'm not aware of any extensions, certainly none in JavaScript, that make doing what you want to do any less painless with a single pattern.)
A better approach would be to keep a dictionary (Object, in JavaScript) that maps from words to counts. Initialize it to your set of words with the appropriate counts for each. You can use a regular expression to match words, and then for each word you find, decrement the corresponding entry in the dictionary. If the dictionary contains any non-0 values at the end, or if somewhere a long the way you try to over-decrement a value (or decrement one that doesn't exist), then you have a failed match.
I'm totally not sure if I get you right there, so I'll just post my suggestion for it.
var query = "trin and is",
target = "This is a random string",
search = { },
matches = 0;
query.split( /\s+/ ).forEach(function( word ) {
search[ word ] = true;
});
Object.keys( search ).forEach(function( word ) {
matches += +new RegExp( word ).test( target );
});
// do something useful with "matches" for the query, should be "3"
alert( matches );
So, the variable matches will contain the number of unique matches for the query. The first split-loop just makes sure that no "doubles" are counted since we would overwrite our search object. The second loop checks for the individuals words within the target string and uses the nifty + to cast the result (either true or false) into a number, hence, +1 on a match or +0.
I was looking for a solution to this issue and none of the solutions presented here was good enough, so this is what I came up with:
function filterMatch(itemStr, keyword){
var words = keyword.split(' '), i = 0, w, reg;
for(; w = words[i++] ;){
reg = new RegExp(w, 'ig');
if (reg.test(itemStr) === false) return false; // word not found
itemStr = itemStr.replace(reg, ''); // remove matched word from original string
}
return true;
}
// test
filterMatch('This is a random string', 'trin and is'); // true
filterMatch('This is a random string', 'trin not is'); // false