Regex to allow only a single dot in a textbox - javascript

I have one text input.
I wrote a regex for masking all special characters except . and -. Now if by mistake the user enters two . (dots) in input, then with the current regex
var valueTest='225..36'
valueTest.match(/[^-.\d]/)
I expected that the number will not pass this condition
How to handle this case. I just want one . (dot) in input field since it is a number.

I think you mean this,
^-?\d+(?:\.\d+)?$
DEMO
It allows positive and negative numbers with or without decimal points.
EXplanation:
^ Asserts that we are at the start.
-? Optional - symbol.
\d+ Matches one or more numbers.
(?: start of non-capturing group.
\. Matches a literal dot.
\d+ Matches one or more numbers.
? Makes the whole non-capturing group as optional.
$ Asserts that we are at the end.

if you just want to handle number ,you can try this:
valueTest.match(/^-?\d+(\.\d+)?$/)

You can probably avoid regex altogether with this case.
For instance
String[] input = { "225.36", "225..36","-225.36", "-225..36" };
for (String s : input) {
try {
Double d = Double.parseDouble(s);
System.out.printf("\"%s\" is a number.%n", s);
}
catch (NumberFormatException nfe) {
System.out.printf("\"%s\" is not a valid number.%n", s);
}
}
Output
"225.36" is a number.
"225..36" is not a valid number.
"-225.36" is a number.
"-225..36" is not a valid number.

Use below reg ex it will meet your requirements.
/^\d+(.\d+)?$/

Related

regex - don't allow name to finish with hyphen

I'm trying to create a regex using javascript that will allow names like abc-def but will not allow abc-
(hyphen is also the only nonalpha character allowed)
The name has to be a minimum of 2 characters. I started with
^[a-zA-Z-]{2,}$, but it's not good enough so I'm trying something like this
^([A-Za-z]{2,})+(-[A-Za-z]+)*$.
It can have more than one - in a name but it should never start or finish with -.
It's allowing names like xx-x but not names like x-x. I'd like to achieve that x-x is also accepted but not x-.
Thanks!
Option 1
This option matches strings that begin and end with a letter and ensures two - are not consecutive so a string like a--a is invalid. To allow this case, see the Option 2.
^[a-z]+(?:-?[a-z]+)+$
^ Assert position at the start of the line
[a-z]+ Match any lowercase ASCII letter one or more times (with i flag this also matches uppercase variants)
(?:-?[a-z]+)+ Match the following one or more times
-? Optionally match -
[a-z]+ Match any ASCII letter (with i flag)
$ Assert position at the end of the line
var a = [
"aa","a-a","a-a-a","aa-aa-aa","aa-a", // valid
"aa-a-","a","a-","-a","a--a" // invalid
]
var r = /^[a-z]+(?:-?[a-z]+)+$/i
a.forEach(function(s) {
console.log(`${s}: ${r.test(s)}`)
})
Option 2
If you want to match strings like a--a then you can instead use the following regex:
^[a-z]+[a-z-]*[a-z]+$
var a = [
"aa","a-a","a-a-a","aa-aa-aa","aa-a","a--a", // valid
"aa-a-","a","a-","-a" // invalid
]
var r = /^[a-z]+[a-z-]*[a-z]+$/i
a.forEach(function(s) {
console.log(`${s}: ${r.test(s)}`)
})
You can use a negative lookahead:
/(?!.*-$)^[a-z][a-z-]+$/i
Regex101 Example
Breakdown:
// Negative lookahead so that it can't end with a -
(?!.*-$)
// The actual string must begin with a letter a-z
[a-z]
// Any following strings can be a-z or -, there must be at least 1 of these
[a-z-]+
let regex = /(?!.*-$)^[a-z][a-z-]+$/i;
let test = [
'xx-x',
'x-x',
'x-x-x',
'x-',
'x-x-x-',
'-x',
'x'
];
test.forEach(string => {
console.log(string, ':', regex.test(string));
});
The problem is that the first assertion accepts 2 or more [A-Za-z]. You will need to modify it to accept one or more character:
^[A-Za-z]+((-[A-Za-z]{1,})+)?$
Edit: solved some commented issues
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('xggg-dfe'); // Logs true
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('x-d'); // Logs true
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('xggg-'); // Logs false
Edit 2: Edited to accept characters only
/^[A-Za-z]+((-[A-Za-z]{1,})+)?$/.test('abc'); // Logs true
Use this if you want to accept such as A---A as well :
^(?!-|.*-$)[A-Za-z-]{2,}$
https://regex101.com/r/4UYd9l/4/
If you don't want to accept such as A---A do this:
^(?!-|.*[-]{2,}.*|.*-$)[A-Za-z-]{2,}$
https://regex101.com/r/qH4Q0q/4/
So both will accept only word starting from two characters of the pattern [A-Za-z-] and not start or end (?!-|.*-$) (negative lookahead) with - .
Try this /([a-zA-Z]{1,}-[a-zA-Z]{1,})/g
I suggest the following :
^[a-zA-Z][a-zA-Z-]*[a-zA-Z]$
It validates :
that the matched string is at least composed of two characters (the first and last character classes are matched exactly once)
that the first and the last characters aren't dashes (the first and last character classes do not include -)
that the string can contain dashes and be greater than 2 characters (the second character class includes dashes and will consume as much characters as needed, dashes included).
Try it online.
^(?=[A-Za-z](?:-|[A-Za-z]))(?:(?:-|^)[A-Za-z]+)+$
Asserts that
the first character is a-z
the second is a-z or hyphen
If this matches
looks for groups of one or more letters prefixed by a hyphen or start of string, all the way to end of string.
You can also use the I switch to make it case insensitive.

Regular expression for decimal number accepting 0 to 4 digits but no characters

I'm trying to devise a regular expression which will accept decimal number up to 4 digits.
I have successfully done it when a user types it in a text box.
Now, I'm trying to validate text box for paste operation.
For that, I have written a jquery function
function pasteNumber() {
var reNumber = /\d*\.\d{0,4}/;
var theString = window.clipboardData.getData('Text');
if (reNumber.test(theString) == false) {
alert("You are trying to paste an invalid Number!")
return;
}
event.srcElement.value = theString
return;
}
The regular expression which I have used is accepting a value like
44.aaaa
which it should not accept.
Then I tried changing regular expression to
/\d*\.\d{1,4}/
Then, it started to accept values like
44.1aaa
I need help to write a regular expression which will accept values like
4.1
421.11
467.111
438904.1111
0.1
But not
1234.a
489.a
435.aaa
412.1aaaa
1567.11a
In short, there should be no characters.
Any suggestions please?
Thank you
You are only missing the anchors ^ and $
^\d*\.\d{0,4}$
See demo
But, to avoid matching . and 123., you can enhance it as
^\d*\.\d{1,4}$
See update.
As for anchors, they
do not match any character at all. Instead, they match a position
before, after, or between characters. They can be used to anchor the
regex match at a certain position. The caret ^ matches the position
before the first character in the string. Applying ^a to abc matches
a. ^b does not match abc at all, because the b cannot be matched right
after the start of the string, matched by ^.
Similarly, $ matches right after the last character in the string. c$ matches c in abc, while a$ does not match at all.
You just need to add some anchors and group (?:) the entire decimal part and make it optional with a ?:
^\d+(?:\.\d{1,4})?$
^ is for start of string, $ is for end of string
See demo

Regex for digits and a plus sign

The conditions of the regex are as follows:
Starts with either digits or a '+' sign and ends with digits.
This is going to be used to validate a certain type of number. What I got so far is:
/^\d*|\+\d*$/
This regex seems to match any string though. How would a regex that matches my conditions look like?
The regex will be used in a JavaScript function.
I think you want something like this,
^(?:[+\d].*\d|\d)$
^ Asserts that we are at the start.
[+\d] Matches a plus symbol or a digit.
.* Matches any character zero or more times.
\d Matches a digit.
| OR
\d A single digit.
$ Asserts that we are at the end.
Use this if you want to match also a line which has a single plus or digit.
^[+\d](?:.*\d)?$
DEMO
You need to use anchors ^ and $ on both sides of your regex and make first part + or digit) optional.
You can use this regex:
^([+\d].*)?\d$
RegEx Demo

Regex to match # followed by square brackets containing a number

I want to parse a pattern similar to this using javascript:
#[10] or #[15]
With all my efforts, I came up with this:
#\\[(.*?)\\]
This pattern works fine but the problem is it matches anything b/w those square brackets. I want it to match only numbers. I tried these too:
#\\[(0-9)+\\]
and
#\\[([(0-9)+])\\]
But these match nothing.
Also, I want to match only pattern which are complete words and not part of a word in the string. i.e. should contain spaces both side if its not starting or ending the script. That means it should not match phrase like this:
abxdcs#[13]fsfs
Thanks in advance.
Use the regex:
/(?:^|\s)#\[([0-9]+)\](?=$|\s)/g
It will match if the pattern (#[number]) is not a part of a word. Should contain spaces both sides if its not starting or ending the string.
It uses groups, so if need the digits, use the group 1.
Testing code (click here for demo):
console.log(/(?:^|\s)#\[([0-9]+)\](?=$|\s)/g.test("#[10]")); // true
console.log(/(?:^|\s)#\[([0-9]+)\](?=$|\s)/g.test("#[15]")); // true
console.log(/(?:^|\s)#\[([0-9]+)\](?=$|\s)/g.test("abxdcs#[13]fsfs")); // false
console.log(/(?:^|\s)#\[([0-9]+)\](?=$|\s)/g.test("abxdcs #[13] fsfs")); // true
var r1 = /(?:^|\s)#\[([0-9]+)\](?=$|\s)/g
var match = r1.exec("#[10]");
console.log(match[1]); // 10
var r2 = /(?:^|\s)#\[([0-9]+)\](?=$|\s)/g
var match2 = r2.exec("abxdcs #[13] fsfs");
console.log(match2[1]); // 13
var r3 = /(?:^|\s)#\[([0-9]+)\](?=$|\s)/g
var match3;
while (match3 = r3.exec("#[111] #[222]")) {
console.log(match3[1]);
}
// while's output:
// 111
// 222
You were close, but you need to use square brackets:
#\[[0-9]+\]
Or, a shorter version:
#\[\d+\]
The reason you need those slashes is to "escape" the square bracket. Usually they are used for denoting a "character class".
[0-9] creates a character class which matches exactly one digit in the range of 0 to 9. Adding the + changes the meaning to "one or more". \d is just shorthand for [0-9].
Of course, the backslash character is also used to escape characters inside of a javascript string, which is why you must escape them. So:
javascript
"#\\[\\d+\\]"
turns into:
regex
#\[\d+\]
which is used to match:
# a literal "#" symbol
\[ a literal "[" symbol
\d+ one or more digits (nearly identical to [0-9]+)
\] a literal "]" symbol
I say that \d is nearly identical to [0-9] because, in some regex flavors (including .NET), \d will actually match numeric digits from other cultures in addition to 0-9.
You don't need so many characters inside the character class. More importantly, you put the + in the wrong place. Try this: #\\[([0-9]+)\\].

How do you only keep numbers and commas and dots (that occur between numbers) with regex?

Say you have the following string:
var string = "This shirt, is very nice. It costs DKK 1.500,00";
I want a function that will return 1.500,00.
The point is, that I only want to allow commas and dots that occur between numbers so I don't end up with: ,.1.500,00
How would you do this using regexp in javascript?
How about this - \b\d[.,\d]*\b ?
This might be the required one:
\d((?=([.,]\d|\d)).)*
\d matches a digit
(?=([.,]\d|\d)) is a look-ahead which ensures that the following character is either a digit or a . or , followed by a digit.
The . matches any character and * allows zero or more occurrence of preceding pattern
This seems to work:
"This shirt, is very nice. It costs DKK ,.1.500,00,.".match(/(\d+\.\d+)+,\d+/g);

Categories