Regular Expression for negative and positive decimal numbers - javascript

I'm trying to create a regular expression using javascript for react application that allow negative and positive decimal numbers and not allow enter any character.
I've been looking for examples, reading documentation but I dont know how make it.
This are the things that have to do:
allow negative and positive decimal numbers, I found this:
var re = new RegExp("^[+-]?[0-9]{0,900}(?:\.[0-9]{0,900})?$");
but I can write a character and show me true and add other character and show me false. console.log(re.test(value));
if is decimal and starts with zero show zero (0.232) and dont allow this (.232)
dont allow write characters, I've seen this /^\d*$/

Looking at the documentation about RegExp it states that when using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
Your regex would then match a dot which would match any character making for example a valid because the preceding [0-9]{0,900} matches zero - 900 times.
Your regex would become:
var re = new RegExp("^[+-]?[0-9]{0,900}(?:\\.[0-9]{0,900})?$");
To match negative and positive decimal numbers that should not start with a dot, you could use:
^[+-]?[0-9]+(?:\.[0-9]+)?$
Which will match the beginning of the string ^, an optional [+-]?, one or more digits [0-9]+ followed by an optional part which will match a dot and one or more digits (?:\.[0-9]+)? and then the end of the string $.
var re = new RegExp("^-?[0-9]+(?:\\.[0-9]+)?$");
var re = new RegExp("^[+-]?[0-9]+(?:\\.[0-9]+)?$");
var strings = [
"1",
"1.2",
"0.232",
".232",
"-1.2",
"+1.2"
];
strings.forEach((s) => {
console.log(s + " ==> " + re.test(s));
});

I use this:
^-?[0-9]\d*(\.\d+)?$
only numbers
positive and negative
dont allow .232

Related

Regex - How to replace a specific character in a string after being typed only once?

I'm trying to limit an input field to only numbers and the possibility of a "+" sign just at the string's [0] index. The idea is to let the user type their phone number, I have come up with this:
function main() {
let phone = document.getElementById('phone');
let phoneRegex = /[a-zA-Z]|[-!$%^&*()_|~=`{}[\]:";'<>?,./]/;
phone.value = phone.value.replace(phoneRegex, '');
console.log(phone.value);
}
<input id="phone">
<button onclick="main()">Run</button>
The thing is, this works fine, but I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.
I can't come up with an idea on how to solve this
Try this as a starting point (you'll probably want to expand it further to account for total string length, delimiters like -, etc.):
let phoneRegex = /\+?\d+/;
+ in a regular expression has a special meaning, so when we want to match the literal character "+" then we need to escape it. And following it with the ? character makes it optional:
\+?
Next, \d followed by + will match any sequence of one or more digits:
\d+
You can see a visualization of this pattern here.
I want to limit the first character to only a digit or a "+"
sign, characters coming from index [1] and on should only
be numbers.
The regex:
/^\+?\d+$/
means:
From the beginning, one or zero + signs, then one or more numbers until the end.
Note the following regex symbols:
* - zero or more
+ - one or more
? - zero or one
I know I'm late in this game, but adding one more solution for me and other's future references.
I came up with this solution which works for me:
/^(\+|[0-9])?[0-9]{12}$/
Thanks

How to convert a camelcased string to sentence cased without excluding any special characters?

How to convert a camelcased string to sentence cased without excluding any special characters?
Suggest a regex for converting camelcased string with special characters and numbers to sentence case?:
const string = `includes:SummaryFromDetailHistory1990-AsAbstract`
Expected outcome:
Includes : Summary From Detail History 1990 - As Abstract
Currently I'm using lodash startCase to convert camelCased to sentenceCase. But the issue with this approach is that it is removing special characters like brackets, numbers, parenthesis, hyphens, colons, etc... (most of the special characters)
So the idea is to convert camelcased strings to sentence cased while preserve the string identity
For example:
const anotherString = `thisIsA100CharactersLong:SampleStringContaining-SpecialChar(s)10&20*`
const expectedReturn = `This Is A 100 Characters : Long Sample String Containing - Special Char(s) 10 & 20 *`
Is that possible with regex?
You'll have to deal with all the cases yourself:
[a-z](?=[A-Z]): lowercase followed by uppercase
[a-zA-Z](?=[0-9]): letter followed by digit
[0-9](?=[a-zA-Z]): digit followed by letter
[a-zA-Z0-9](?=[^a-zA-Z0-9]): letter or digit followed by neither letter nor digit (\w and \W could be used, but they cover _ too, so up to you)
[^a-zA-Z0-9](?=[a-zA-Z0-9]): not letter nor digit following by either letter or digit
etc.
Then, you can or them together:
([a-z](?=[A-Z])|[a-zA-Z](?=[0-9])|[0-9](?=[a-zA-Z])|[a-zA-Z0-9](?=[^a-zA-Z0-9])|[^a-zA-Z0-9](?=[a-zA-Z0-9]))
And replace by:
$1
(see the space after $1).
See https://regex101.com/r/4AVbAs/1 for instance.
You will hit edge cases though, e.g. Char(s), so you'll need special rules for the parens for instance (see the following section about lookbehinds that can help for that). A bit of a tough job, quite error prone too and hardly maintainable I'm afraid.
If lookbehinds were allowed, you would not need to capture the first char in each group, but wrap the left patterns in (?<=...) and replace by a simple space directly:
(?<=[a-z])(?=[A-Z]): preceded by lowercase, followed by uppercase
(?<=[a-zA-Z])(?=[0-9]): preceded by letter, followed by digit
(?<=[0-9])(?=[a-zA-Z]): preceded by digit, followed by letter
(?<=[a-zA-Z0-9])(?=[^a-zA-Z0-9])(?!(?:\(s)?\)): preceded by letter or digit, followed by not letter nor digit, as well as not followed by (s) nor )
(?<=[^a-zA-Z0-9])(?<!\()(?=[a-zA-Z0-9]): preceded by not letter nor digit, as well as not preceded by (, followed by letter or digit
or-ed together:
(?<=[a-z])(?=[A-Z])|(?<=[a-zA-Z])(?=[0-9])|(?<=[0-9])(?=[a-zA-Z])|(?<=[a-zA-Z0-9])(?=[^a-zA-Z0-9])(?!(?:\(s)?\))|(?<=[^a-zA-Z0-9])(?<!\()(?=[a-zA-Z0-9])
Replace with an empty space, see https://regex101.com/r/DB91DE/1.
The wanted result doesn't seem to be regular, some special characters are supposed to be preceeded with a space and some are not. Treating the parenthesis like you want is a bit tricky. You can use function to handle the parenthesis, like this:
let parenth = 0;
const str = `thisIsA100CharactersLong:SampleStringContaining-SpecialChar(s)10&20*`,
spaced = str.replace(/[A-Z]|\d+|\W/g, (m) => {
if (m === '(') {
parenth = 1;
return m;
}
if (parenth || m === ')') {
parenth = 0;
return m;
}
return ` ${m}`;
});
console.log(spaced);
If the data can contain other brackets, instead of just checking parentheses, use a RexExp to test any opening bracket: if (/[({[]/.test(m)) ..., and test for closing brackets: if (/[)}\]]/.test(m)) ....
You can test the snippet with different data at jsFiddle.
This is impossible. You cannot do this in regex. You will have to consider exceptions...

Regex to reject names ending in non-letters except dot

I have written a regex that returns true or false depending on whether the text provided is a valid first/last name:
let letters = `a-zA-Z`;
letters += `àáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšž`;
letters += `ÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð`;
const re = new RegExp(`^[${letters}][${letters} ,.'’-]+[${letters}.]$`, 'u')
return(name.match(re));
So far, I'm able to ensure it only validates names that actually start with a letter and do not contain numerals or any special characters other than dot, hyphen, or comma. However, it still rejects names like Jo and Xi. I understand it's due to the three separate $-blocks. But the blocks are there to ensure the name doesn't start with a non-letter or end in a non-letter other than dot. How should I modify my expression to accommodate this?
Also, is there any way to shorten this expression without compromising its range? I still need it to cover extended Latin characters.
If the minimum length of the word is 2 chars, you could use a negative lookahead ^(?!.*[ ,'’]$) to assert that the string does not end with the characters that you would not allow and leave out the last [${letters}.]
Regex demo
If the minimum length is 1, you could use another negative lookahead (?![ .,'’]) and add the dot as well so that a single dot is not allowed at the beginning and then use the single character class that contains all allowed characters.
^(?!.*[ ,'’]$)(?![ .,'’])[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'’-]+$
Regex demo

Regular Expression in Javascript to start with Uppercase, only alphabets, maxlength 20, minlength 2

I can validate this rule using plain Javascript. But I would prefer to do it using RegEx. I tried this (and other variations) but am not too confident:
regEx = /^[A-Z]([a-z]|[A-Z]){1,19}$/;
Test cases did go through. Is this the right way or is there a better approach?
You may need a tool for build your regEx like https://regex101.com
What do you want to match exactly ?
Your regex match the following string:
- Start by a character between [A-Z] => only alphabetical upper case
- 1 to 19 alphabetical character either upper or lower case
So your string length is between 2 and 20 characters.
You could simply your regExp by
regEx = /^[A-Z][a-zA-Z]{1,19}$/;
If you want no min length, mean that empty string match you could use:
regEx = /^([A-Z][a-zA-Z]{0,19})?$/
If you want min lenght to be 1, means that you match single upper character you could use:
regEx = /^[A-Z][a-zA-Z]{0,19}$/

Regular expression to match a number range in JavaScript

I'm having problem with JavaScript regular expressions. I want to match real numbers form 1 to 5. Precission is in two digits. My code is but it doesnt work.
function validate_prosjek(nmb)
{
var pattern= new RegExp(/[1-4]\.[0-9][0-9]|5\.00/);
return pattern.test(nmb);
}
It recognizes real numbers higher than 5.
You need to "anchor" your regexp with ^ and $ to match the beginning and end of the string, respectively:
var pattern = /^([1-4]\.[0-9][0-9]|5\.00)$/;
You also need to escape the . because it's a special character in regexps, and there's no need to call new RegExp if the regexp is already in /.../ synax.

Categories

Resources