I am looking for a regular expression in js where as it can accept anything say numbers,characters,special characters etc but no two or more consecutive special characters. Tried different combinations, but could not succeed.
for example:
abcd -- valid
abcd # dfds -- valid
abcd## ssf -- invalid
hi#try$example#test - valid
hi######hello --- invalid
This regExp returns true for hi######hello, you can invert results as you like:
var regExp = /(?:.)*(?:[#$&#?]{2})+(?:.)*/g // #$&#? - your symbols go here
regExp.test("hi######hello"); // true
regExp.test("hi#try$example#test"); // false
Related
I've written a basic 2 operand calculator app (+ - * /) that uses a couple of inline regex validations to filter away invalid characters as they are typed.
An example looks like:
//check if operator is present
if(/[+\-*\/]/.test(display1.textContent)){
//validate the string each time a new character is added
if(!/^\d+\.?\d*[+\-*\/]?\d*\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
//validate the string character by character before operator
} else {
if(!/^\d+\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
}
In the above, a valid character doesn't return false:
23.4x0.00025 (no false returned and hence the string is typed out)
But, if an invalid character is typed the function returns false and the input is filtered away:
23.4x0.(x) x at the end returns a false so is filtered (only one operator allowed per calculation)
23.4x0. is typed
It works pretty well but allows for the following which I would like to deal with:
2.+.1
I would prefer 2.0+0.1
My regex would need an if-then-else conditional stating that if the current character is '.' then the next character must be a number else the next char can be number|.|operator. Or if the current character is [+-*/] then the next character must be a number, else the next char can be any char (while following the overall logic).
The tricky part is that the logic must process the string as it is typed character by character and validate at each addition (and be accurate), not at the end when the string is complete.
if-then-else regex is not supported in JavaScript (which I think would satisfy my needs) so I need to use another approach whilst remaining within the JS domain.
Any suggestions about this specific problem would be really helpful.
Thanks
https://github.com/jdineley/Project-calculator
Thanks #trincot for the tips using capturing groups and look around. This helped me write what I needed:
https://regex101.com/r/khUd8H/1
git hub app is updated and works as desired. Now just need to make it pretty!
For ensuring that an operator is not allowed when the preceding number ended in a point, you can insert a positive look behind in your regex that requires the character before an operator to always be a digit: (?<=\d)
Demo:
const validate = s => /^(\d+(\.\d*)?((?<=\d)[+*/-]|$))*$/.test(s);
document.querySelector("input").addEventListener("input", function () {
this.style.backgroundColor = validate(this.value) ? "" : "orange";
});
Input: <input>
Following is my regex to accept only chinese characters and English numbers in a textbox but its failing for some scenarios like below mentioned. Let me know what I am doing wrong here.
Regex -
const regex = /[\u4E00-\u9FFF\u3400-\u4DFF\uF900-\uFAFF0-9]+/g
Failing cases -
090 asffa
0342eq###
42242442dsfsfs
React Example code setup - https://codepen.io/anon/pen/dLQJKM
Your pattern is checking if the input contains at least one such character.
As long as there will be either a number, or a Chinese character, it will consider your input as valid.
What you want is to find if there is any character that do not match this pattern. To do so, you simply need to use a negated character class [^... and then check if string.match(regex) is falsy.
const reg = /[^\u4E00-\u9FFF\u3400-\u4DFF\uF900-\uFAFF0-9]+/g;
const test = txt => {
console.log(txt, !txt.match(reg));
};
test('090 asffa'); // false
test('0342eq###'); // false
test('42242442dsfsfs'); // false
test('foo我'); // false
test('245我吧'); // true
test('245'); // true
test('我吧'); // true
I have a question related to formatting strings.
User should parse a string in the Format XX:XX.
if the string parsed by user is in the format XX:XX i need to return true,
else false:
app.post('/test', (req, res) => {
if (req.body.time is in the format of XX:XX) {
return true
} else {
return false
}
});
You can use the RegExp.test function for this kind of thing.
Here is an example:
var condition = /^[a-zA-Z]{2}:[a-zA-Z]{2}$/.test("XX:XX");
console.log("Condition: ", condition);
The regex that I've used in this case check if the string is composed from two upper or lower case letters fallowed by a colon and other two such letters.
Based on your edits it seems that you're trying to check if a string represents an hour and minute value, if that is the case, a regex like this will be more appropriate /^\d{2}:\d{2}$/. This regex checks if the string is composed of 2 numbers fallowed by a colon and another 2 numbers.
The tool you're looking for is called Regular Expressions.
It is globally supported in almost every development platform, which makes it extremely convenient to use.
I would recommend this website for working out your regular expressions.
/^[a-zA-Z]{2}:[a-zA-Z]{2}&/g is an example of a Regular Expression that will take any pattern of:
[a-zA-Z]{2} - two characters from the sets a-z and A-Z.
Followed by :
Followed by the same first argument. Essentially, validating the pattern XX:XX. Of course, you can manipulate it as to what you want to allow for X.
^ marks the beginning of a string and $ marks the end of it, so ASD:AS would not work even though it contains the described pattern.
try using regex
var str = "12:aa";
var patt = new RegExp("^([a-zA-Z]|[0-9]){2}:([a-zA-Z]|[0-9]){2}$");
var res = patt.test(str);
if(res){ //if true
//do something
}
else{}
I am holding in a field the validation format that I would need.
I need to convert different ## into a regex validation.
Is there a simple replace that can do this for me.
for example, i need to validate the account number.
sometimes it might need to be ###-###, or I'll get ####### or ##-####.
depending what is in the id="validationrule" field
I'm looking for
regex = $('#validationrule').replace("#", "[0/9]");
It also has to take into consideration that sometimes there is a dash in there.
Your question seems to be about creating regexes from a string variable (which you get from an input field that specifies the validation format).
"###-###" might turn into /^\d{3}\-\d{3}$/
"#######" might turn into /^\d{7}$/
If your validation format is built from the 2 characters # and -, this would work:
function createValidationRegEx(format){
format = format
.replace(/[^#\-]/g, '') //remove other chars
.replace(/#/g, '\\d') //convert # to \d
.replace(/\-/g, '\\-'); //convert - to \-
return new RegExp('^' + format + '$', 'g');
}
//create regexes
var format1 = createValidationRegEx('###-###');
var format2 = createValidationRegEx('#######');
//test regexes
console.log(format1.test('123-456')); // true
console.log(format2.test('123-456')); // false
console.log(format1.test('1234567')); // false
console.log(format2.test('1234567')); // true
Please note that you need to pay attention to which characters needs to be escaped when creating regexes from strings. This answer provides more details about how to solve this more generally, if you want to build more complex solutions.
If you are trying to replace the .value of an <input> element you can use .val(function), return replacement string from .replace() inside of function, chain .val() to assign result to regex. Use RegExp constructor with g flag to replace all matches of the RegExp supplied to .replace() to match characters against at string.
var regex = $("#validationrule").val(function(_, val) {
return val.replace("#", "[0/9]");
}).val();
console.log(regex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="validationrule" value="#">
I have string patterns like name1|value1, name1|value1,name2|value2, name1| and name1|value1,. I have to have Regular expression to find the given pattern is true or false
Input and output would be
"name1|value1" -> true
"name1|value1,name2|value2" -> true
"name1|" -> false
"name1|value1," -> false
"name1|value1,name2" -> false
"name1|value1,name2|" -> false
Pretty simple: ^\w+\|\w+(,\w+\|\w+)*$
The first portion, ^\w+\|\w+ looks to make sure the string starts with at least 1 completed name|value pair.
Then the second portion, (,\w+\|\w+)* says that same pattern may repeat infinitely as long as there is a comma between the first pair and all subsequent pairs. (Although, the asterisk quantifies that the second portion of the pattern may not occur at all.)
Finally the $ says that the string must end matching this pattern. (I.e., this pattern cannot only match part of the string. It must match the entire string because of the ^ and $.)
To format this pattern for javascript, simply throw a forward slashes on both ends, so: /^\w+\|\w+(,\w+\|\w+)*$/ The pattern should not require any flags.
It is worth noting, if you need to match more complex names/values that are outside the character range of \w, then you should replace all \ws with [Some Character Set(s)].
If your have multiple pairs to check, you can apply your regex on splitted string elements with an every function:
isValidPairs = function(str) {
return str.split(',').every(function(elt) {
return /^\w+\|\w+$/.test(elt);
});
}
pairsArr = ["nam1|val1", "nam1|val1,name2|val2", "nam1|", "nam1|val1,", "nam1|val1,name", "nam1|val1,name|"];
pairsArr.forEach(function(str) {
console.log('%s: %s:', str, isValidPairs(str));
});