return number and word regex javascript - javascript

can someone tell me why my code keeps returning null, it used to return a match now its not and i dont know whats wrong. I want it to find a match in the string for 1 hour
var error = "null";
var str = "1 hour "
var strCheck = str.match(/[1]\s[hour]\s/g);
if(String(strCheck) != error) {
alert("works!");
}

Check this..
var error = "null";
var str = "1 hour "
var strCheck = str.match(/1 hour /g);
if(strCheck != error) {
alert("works!");
}
Explanation:
[] is used to match a single character so [hour] is not correct and if you have change in number of hours you can make it like this:
var error = "null";
var str = "1 hour "
var strCheck = str.match(/[0-9][0-9] hour /g);
if(strCheck != error) {
alert("works!");
}
or Simply use \d to find a digit and \d+ to find one or more digit.
For more see this its simple and clear.

The RegEx [1]\s[hour]\s will not work. The character class without quantifiers [] is used to match only a single character from the characters within it. So, [hour] will match one of the character from h, o, u and r. However, you want to match hour as complete string.
To make the regex more dynamic and match even 10 hours following regex can be used.
/\d+\s*hours?\s*/
Code:
var error = "null";
var str = "1 hour "
var strCheck = str.match(/\d+\s*hours?\s*/g);
if (strCheck != null) {
alert("works!");
}
console.log(strCheck);
If you just want to check if the string contain a pattern, use RegExp#test instead of String#match.
/\d+\s*hours?\s*/.test(str)

I don't know what kind of validation you need with that regex, but this can be useful:
\d+\s(hour(s)?)
Explanation:
\d+ One or more digits
\s A blank space
(hour(s)?) a string hour with optional s at the end for plural.
The match() method returns an array with the results or null if no match was found. So I suggest you simply check the result as a boolean instead of compare to "null" string. Then you code could be like this:
var strCheck = str.match(/\d+\s(hour(s)?)/, g);
if (strCheck) {
alert("works!");
}
Some cases here.

Related

I need help getting the first n characters of a string up to when a number character starts

I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)

javascript - regexp exec internal index doesn't progress if first char is not a match

I need to match numbers that are not preceeded by "/" in a group.
In order to do this I made the following regex:
var reg = /(^|[^,\/])([0-9]*\.?[0-9]*)/g;
First part matches start of the string and anything else except "/", second part matches a number. Everything works ok regarding the regex (it matches what I need). I use https://regex101.com/ for testing. Example here: https://regex101.com/r/7UwEUn/1
The problem is that when I use it in js (script below) it goes into an infinite loop if first character of the string is not a number. At a closer look it seems to keep matching the start of the string, never progressing further.
var reg = /(^|[^,\/])([0-9]*\.?[0-9]*)/g;
var text = "a 1 b";
while (match = reg.exec(text)) {
if (typeof match[2] != 'undefined' && match[2] != '') {
numbers.push({'index': match.index + match[1].length, 'value': match[2]});
}
}
If the string starts with a number ("1 a b") all is fine.
The problem appears to be here (^|[^,/]) - removing ^| will fix the issue with infinite loop but it will not match what I need in strings starting with numbers.
Any idea why the internal index is not progressing?
Infinite loop is caused by the fact your regex can match an empty string. You are not likely to need empty strings (even judging by your code), so make it match at least one digit, replace the last * with +:
var reg = /(^|[^,\/])([0-9]*\.?[0-9]+)/g;
var text = "a 1 b a 2 ana 1/2 are mere (55";
var numbers=[];
while (match = reg.exec(text)) {
numbers.push({'index': match.index + match[1].length, 'value': match[2]});
}
console.log(numbers);
Note that this regex will not match numbers like 34. and in that case you may use /(^|[^,\/])([0-9]*\.?[0-9]+|[0-9]*\.)/g, see this regex demo.
Alternatively, you may use another "trick", advance the regex lastIndex manually upon no match:
var reg = /(^|[^,\/])([0-9]*\.?[0-9]+)/g;
var text = "a 1 b a 2 ana 1/2 are mere (55";
var numbers=[];
while (match = reg.exec(text)) {
if (match.index === reg.lastIndex) {
reg.lastIndex++;
}
if (match[2]) numbers.push({'index': match.index + match[1].length, 'value': match[2]});
}
console.log(numbers);

Match joined AmPm hours with regex

I have input string in next format : 12:00am|1:20PM|9:30Pm
I need to have in output array of hours like : [12:00am, 1:20PM, 9:30Pm]
But before I shoudl match it with regex.
I have some regex to match AmPm hours and I tried to add | to match full string
\b((1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm]))([|])?. This regex matches string 12:00am|1:20PM|9:30Pm but also matches string 12:00am|1:20PM}9:30Pm which isn't correct.
Where is my mistake in my regex and how can I return expected array.
Thanks
The \b((1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm]))([|])? does not require | as [|]? matches 1 or 0 occurrences of this char. This regex matches 12:00am|1:20PM}9:30Pm as it finds 12:00am and calls it a day (i.e. returns a valid match).
You need to split the string with | and validate each item against /^(1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm])$/ pattern.
var s = "12:00am|1:20PM|9:30Pm";
var re = /^(1[0-2]|0?[1-9]):[0-5][0-9]([AaPp][Mm])$/;
var items = s.split("|");
if (items.filter(function(x) { return re.test(x); }).length === items.length) {
console.log("VALID => ", items);
} else {
console.log("INVALID!");
}
Note you may use a regex to pre-validate the string, but it is just more cumbersome:
var s = "12:00am|1:20PM|9:30Pm";
var re_block = "(1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm])";
var re = new RegExp("^" + re_block + "(?:\\|" + re_block + ")*$");
var isValid = re.test(s);
console.log(isValid ? s.split("|") : "Invalid!");
The regex will look like /^(1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm])(?:\|(1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm]))*$/ and it will validate a string that starts with the time substring, and then has 0 or more occurrences of time substrings up to the string end. See the pattern demo.

Retrieving several capturing groups recursively with RegExp

I have a string with this format:
#someID#tn#company#somethingNew#classing#somethingElse#With
There might be unlimited #-separated words, but definitely the whole string begins with #
I have written the following regexp, though it matches it, but I cannot get each #-separated word, and what I get is the last recursion and the first (as well as the whole string). How can I get an array of every word in an element separately?
(?:^\#\w*)(?:(\#\w*)+) //I know I have ruled out second capturing group with ?: , though doesn't make much difference.
And here is my Javascript code:
var reg = /(?:^\#\w*)(?:(\#\w*)+)/g;
var x = null;
while(x = reg.exec("#someID#tn#company#somethingNew#classing#somethingElse#With"))
{
console.log(x);
}
And here is the result (Firebug, console):
["#someID#tn#company#somet...sing#somethingElse#With", "#With"]
0
"#someID#tn#company#somet...sing#somethingElse#With"
1
"#With"
index
0
input
"#someID#tn#company#somet...sing#somethingElse#With"
EDIT :
I want an output like this with regular expression if possible:
["#someID", "#tn", #company", "#somethingNew", "#classing", "#somethingElse", "#With"]
NOTE that I want a RegExp solution. I know about String.split() and String operations.
You can use:
var s = '#someID#tn#company#somethingNew#classing#somethingElse#With'
if (s.substr(0, 1) == "#")
tok = s.substr(1).split('#');
//=> ["someID", "tn", "company", "somethingNew", "classing", "somethingElse", "With"]
You could try this regex also,
((?:#|#)\w+)
DEMO
Explanation:
() Capturing groups. Anything inside this capturing group would be captured.
(?:) It just matches the strings but won't capture anything.
#|# Literal # or # symbol.
\w+ Followed by one or more word characters.
OR
> "#someID#tn#company#somethingNew#classing#somethingElse#With".split(/\b(?=#|#)/g);
[ '#someID',
'#tn',
'#company',
'#somethingNew',
'#classing',
'#somethingElse',
'#With' ]
It will be easier without regExp:
var str = "#someID#tn#company#somethingNew#classing#somethingElse#With";
var strSplit = str.split("#");
for(var i = 1; i < strSplit.length; i++) {
strSplit[i] = "#" + strSplit[i];
}
console.log(strSplit);
// ["#someID", "#tn", "#company", "#somethingNew", "#classing", "#somethingElse", "#With"]

Remove special character from the starting of a string and search # symbol.in javascript

I want to remove special characters from the starting of the string only.
i.e, if my string is like {abc#xyz.com then I want to remove the { from the starting. The string shoould look like abc#xyz.com
But if my string is like abc{#xyz.com then I want to retain the same string as it is ie., abc{#xyz.com.
Also I want to check that if my string has # symbol present or not. If it is present then OK else show a message.
The following demonstrates what you specified (or it's close):
var pat = /^[^a-z0-9]*([a-z0-9].*?#.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '#' somewhere
var testString = "{abc#xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; } //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = ""; alert(testString + " does not conform to pattern"); }
adjustedString;
I have used two separate regex objects to achieve what you require .It checks for both the conditions in the string.I know its not very efficient but it will serve your purpose.
var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^#]*$)/);
var str = "abc#gmail.com";
if(!regex1.test(str)){
if(regex.test(str))
alert("Bracket found at the beginning")
else
alert("Bracket not found at the beginning")
}
else{
alert("doesnt contain #");
}
Hope this helps

Categories