Regular expression for check number and + - javascript

Sorry for very useless question!
I need regular expression for check this type of string
+7
i was try .replace(/^+[0-9][^\d]/g, '') but it give me all another type of math symbols, i need
First symbol +
Second one number 1 - 9

your regex needs to be
^\+[0-9][^\d]
if you want to match all numbers starting with + you can use
/\+\d+/g
Note this would match +73ab and return +73
If you want just numbers you can use
/\b\+\d+\b/g

Plus + is a special character used in regular expressions to indicate one or more occurrences of the expression before it. That's why it does not work in your example. You should escape it with \.
If you want to get all numbers prefixed by plus in multiline text, you can use:
/\+\d+/gm
For Example:
var numbers = 'skdlfjlk +7fsd \r\nsd;flk+123'.match(/\+\d+/gm);
console.log(numbers); // => ["+7", "+123"]
If by "number" you actually meaning digit from 1 to 9, and you are interested only in first occurrence in the string, you can use:
/\+[1-9]/m
If, in addition, you need it to be the beginning of the string, you can use just:
/^\+[1-9]/

Related

Regex replace not removing characters properly

I have the regular expression:
const regex = /^\d*\.?\d{0,2}$/
and its inverse (I believe) of
const inverse = /^(?!\d*\.?\d{0,2}$)/
The first regex is validating the string fits any positive number, allowing a decimal and two decimal digits (e.g. 150, 14., 7.4, 12.68). The second regex is the inverse of the first, and doing some testing I'm fairly confident it's giving the expected result, as it only validates when the string is anything but a number that may have a decimal and two digits after (e.g. 12..05, a5, 54.357).
My goal is to remove any characters from the string that do not fit the first regex. I thought I could do that this way:
let myString = '123M.45';
let fixed = myString.replace(inverse, '');
But this does not work as intended. To debug, I tried having the replace character changed to something I would be able to see:
let fixed = myString.replace(inverse, 'ZZZ');
When I do this, fixed becomes: ZZZ123M.45
Any help would be greatly appreciated.
I think I understand your logic here trying to find a regex that is the inverse of the regex that matches your valid string, in the hopes that it will allow you to remove any characters that make your string invalid and leave only the valid string. However, I don't think replace() will allow you to solve your problem in this way. From the MDN docs:
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
In your inverse pattern you are using a negative lookahead. If we take a simple example of X(?!Y) we can think of this as "match X if not followed by Y". In your pattern your "X" is ^ and your "Y" is \d*\.?\d{0,2}$. From my understanding, the reason you are getting ZZZ123M.45 is that it is finding the first ^ (i.e, the start of the string) that is not followed by your pattern \d*\.?\d{0,2}$, and since 123M.45 doesn't match your "Y" pattern, your negative lookahead is satisfied and the beginning of your string is matched and "replaced" with ZZZ.
That (I think) is an explanation of what you are seeing.
I would propose an alternative solution to your problem that better fits with how I understand the .replace() method. Instead of your inverse pattern, try this one:
const invalidChars = /[^\d\.]|\.(?=\.)|(?<=\.\d\d)\d*/g
const myString = '123M..456444';
const fixed = myString.replace(invalidChars, '');
Here I am using a pattern that I think will match the individual characters that you want to remove. Let's break down what this one is doing:
[^\d\.]: match characters that are not digits
\.(?=\.): match . character if it is followed by another . character.
(?<=\.\d\d)\d*: match digits that are preceded by a decimal and 2 digits
Then I join all these with ORs (|) so it will match any one of the above patterns, and I use the g flag so that it will replace all the matches, not just the first one.
I am not sure if this will cover all your use cases, but I thought I would give it a shot. Here's a link to a breakdown that might be more helpful than mine, and you can use this tool to tweak the pattern if necessary.
I don't think you can do this
remove any characters from the string that do not fit the first regex
Because regex matching is meant for the entire string, and replace is used to replace just a PART inside that string. So the Regex inside replace must be a Regex to match unwanted characters only, not inverted Regex.
What you could do is to validate the string with your original regex, then if it's not valid, replace and validate again.
//if (notValid), replace unwanted character
// replace everything that's not a dot or digit
const replaceRegex = /[^\d.]/g; // notice g flag here to match every occurrence
const myString = '123M.45';
const fixed = myString.replace(replaceRegex, '');
console.log(fixed)
// validate again

Extracting decimal number upto two precision using regex in Javascript [duplicate]

I need some regex that will match only numbers that are decimal to two places. For example:
123 = No match
12.123 = No match
12.34 = Match
^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$
var regexp = /^[0-9]*(\.[0-9]{0,2})?$/;
//returns true
regexp.test('10.50')
//returns false
regexp.test('-120')
//returns true
regexp.test('120.35')
//returns true
regexp.test('120')
If you're looking for an entire line match I'd go with Paul's answer.
If you're looking to match a number witihn a line try: \d+\.\d\d(?!\d)
\d+ One of more digits (same as [0-9])
\. Matches to period character
\d\d Matches the two decimal places
(?!\d) Is a negative lookahead that ensure the next character is not a digit.
It depends a bit on what shouldn't match and what should and in what context
for example should the text you test against only hold the number? in that case you could do this:
/^[0-9]+\.[0-9]{2}$/
but that will test the entire string and thus fail if the match should be done as part of a greater whole
if it needs to be inside a longer styring you could do
/[0-9]+\.[0-9]{2}[^0-9]/
but that will fail if the string is is only the number (since it will require a none-digit to follow the number)
if you need to be able to cover both cases you could use the following:
/^[0-9]+\.[0-9]{2}$|[0-9]+\.[0-9]{2}[^0-9]/
You can also try Regular Expression
^\d+(\.\d{1,2})?$
or
var regexp = /^\d+\.\d{0,2}$/;
// returns true
regexp.test('10.5')
or
[0-9]{2}.[0-9]{2}
or
^[0-9]\d{0,9}(\.\d{1,3})?%?$
or
^\d{1,3}(\.\d{0,2})?$

Regex pattern in Javascript

I want to match a string pattern which has first 4 characters, then the "|" symbol, then 4 characters, then the "|" symbol again and then a minimum of 7 characters.
For example, "test|test|test123" should be matched.
I tried RegExp("^([a-za-z0-9-|](4)[a-za-z0-9-|](5)[a-za-z0-9-|](3)+)$") for this, but it didn't match my test case.
test|test|test1234
Ramesh, does this do what you want?
^[a-zA-Z0-9-]{4}\|[a-zA-Z0-9-]{4}\|[a-zA-Z0-9-]{7,}$
You can try it at https://regex101.com/r/jilO6O/1
For example, the following will be matched:
test|test|test123
a1-0|b100|c10-200
a100|b100|c100200
But the following will not:
a10|b100|c100200
a100|b1002|c100200
a100|b100|c10020
Tips on modifying your original code.
You have "a-za-z" where you probably intended "a-zA-Z", to allow either upper or lower case.
To specify the number of characters to be exactly 4, use "{4}". You were nearly there with your round brackets, but they need to be curly, to specify a count.
To specify a range of number of characters, use "{lowerLimit,upperLimit}". Leaving the upper limit blank allows unlimited repeats.
We need to escape the "|" character because it has the special meaning of "alternate", in regular expressions, i.e. "a|b" matches either "a" or "b". By writing it as "\|" the regex interpreter knows we want to match the "|" character itself.

Javascript regex, replace all characters other than numbers

I would like to replace all the characters other than 0-9 in a string, using Javascript.
Why would this regex not work ?
"a100.dfwe".replace(/([^0-9])+/i, "")
You need the /g modifier to replace every occurrence:
"a100.dfwe".replace(/[^0-9]+/g, "");
I also removed the redundant i modifier and the unused capturing sub-expression braces for you. As others have pointed out, you can also use \D to shorten it even further:
"a100.dfwe".replace(/\D+/g, "");
\D means “not digit”:
"a100.dfwe".replace(/\D/g, "")
What about negative numbers:
Using Andy E's example works unless you have a negative number. Then it removes the '-' symbol also leaving you with an always positive number (which might be ok). However if you want to keep number less than 0 I would suggest the following:
"a-100.dfwe".replace(/(?!-)[^0-9.]/g, "") //equals -100
But be careful, because this will leave all '-' symbols, giving you an error if your text looks like "-a-100.dfwe"
It doesn't work because the character class [^0-9] (= anything but digits) with the repetition modifier + will only match one sequence of non-numeric characters, such as "aaa".
For your purpose, use the /g modifier as the others suggest (to replace all matches globally), and you could also use the pre-defined character class \D (= not a digit) instead of [^0-9], which would result in the more concise regex /\D+/.
"string#! 134".replace(/[^a-z^0-9]+/g, " ");
this would return "string 134"
Based off of #user3324764's answer - Make a prototype function and convert the number to a number.
String.prototype.extractNumber = function ()
{
return Number(this.replace(/(?!-)[^0-9.]/g, ""));
};
Example:
"123.456px".extractNumber(); // 123.456

regular expression negation

In my current regular expression, I am negating digits:
$(function(){
$("#somewhat").bind("keyup",
function(event) {
var regex = /^[\D]*$/;
alert(regex.test($("#somewhat").val()));
});
});
What I have in my mind is to add some special characters on which I should negate, !##$%^&*()_+=<>.?/~`:;" , and leaving dash, apostrophe ( -' ) to the valid list. I'm still kind of dizzy on this regular expression thing. To test with, I added + on the regex,
var regex = /^[\D+]*$/;
When I test it, the alert box returns TRUE, which is not I am expecting.
Inside [ ] please add all the characters you don't want to allow.
/^((?![\d!##$%^&*()_+=<>.?/~`:;"]).)*$/
But can we rely on negating given characters ? because user will be able to enter any character other than these. If you want to allow non-English characters, I would suggest you to use Unicode ranges
see this : http://kourge.net/projects/regexp-unicode-block
[\D+] means "any character that is +, or that is not a digit"; so it's actually equivalent to plain old \D or [\D], since + itself isn't a digit.
To get the meaning of "any character that is neither + nor a digit", you'd have to write [^\d+].
(\D or [\D] is equivalent to [^\d], but its negative-ness doesn't extend beyond that.)

Categories