javascript regex float number which ends with string - javascript

Learning regex but this one gives me a headache. I need to match a float number (with either . or , as decimal point) and it MUST end with the following characters: €/g.
Valid matches should be for example:
40€/g
43.33€/g
40,2€/g
40.2€/g
38.943€/g
Appreciate help..

The regex will look like:
\d+(?:[.,]\d+)?€/g
In Javascript, as a regex object (note that the forward slash needs to be escaped):
/\d+(?:[.,]\d+)?€\/g/
Here's a breakdown of what each part does:
\d+ # one or more digits
(?: # ... don't capture this group separately
[.,] # decimal point
\d+ # one or more digits
)? # make the group optional
€/g # fixed string to match
If you want to allow something like .123€/g to be valid as well, you can use:
(?=[.,]|\d)(?:\d+)?(?:[.,]\d+)?€/g
That is, both the groups of digits are optional, but at least one must be present (this uses lookahead, which is a bit more tricky).
Note that this will also match constructions like 'word2€/g'. If you want to prevent this, start the regex with (?<=^|\s) (matches if preceded by a space or the start of the string) and end it with (?=$|\s) (matches if followed by a space or the end of the string).
Full-blown version:
(?<=^|\s)(?=[.,]|\d)(?:\d+)?(?:[.,]\d+)?€/g(?=$|\s)

\d+([.,]\d+)?€/g
should work, I guess.

Are you really sure you need a regex for this? It might be easier to instead leverage the builtin floating point parsing that is available: take whatever comes before the euro sign, normalize commas to decimals (or vice versa, whatever ends up working) and then try to parse it with the Number function. Note that you would need to check if the conversion worked with the Number.isNaN function.
Another possibility is to just use the parseFloat function. Since it ignores any characters after the numbers then it would parse "40€ as 40.0. However, it might not be what you want since it would also allow things like "40a" and "40b" as well.

Related

Regex - must contain number and must not contain special character

I want to check by regex if:
String contains number
String does not contain special characters (!<>?=+#{}_$%)
Now it looks like:
^[^!<>?=+#{}_$%]+$
How should I edit this regex to check if there is number anywhere in the string (it must contain it)?
you can add [0-9]+ or \d+ into your regex, like this:
^[^!<>?=+#{}_$%]*[0-9]+[^!<>?=+#{}_$%]*$
or
^[^!<>?=+#{}_$%]*\d+[^!<>?=+#{}_$%]*$
different between [0-9] and \d see here
Just look ahead for the digit:
var re = /^(?=.*\d)[^!<>?=+#{}_$%]+$/;
console.log(re.test('bob'));
console.log(re.test('bob1'));
console.log(re.test('bob#'))
The (?=.*\d) part is the lookahead for a single digit somewhere in the input.
You only needed to add the number check, is that right? You can do it like so:
/^(?=.*\d)[^!<>?=+#{}_$%]+$/
We do a lookahead (like peeking at the following characters without moving where we are in the string) to check to see if there is at least one number anywhere in the string. Then we do our normal check to see if none of the characters are those symbols, moving through the string as we go.
Just as a note: If you want to match newlines (a.k.a. line breaks), then you can change the dot . into [\W\w]. This matches any character whatsoever. You can do this in a number of ways, but they're all pretty much as clunky as each other, so it's up to you.

JavaScript regular expression match amount

I'm trying to write a regular expression to match amounts. In my case, what I need is that either the amount should be a positive integer or if the decimal is used, it must be followed by one or two integers. So basically, the following are valid amounts:
34000
345.5
876.45
What I wrote was this: /[0-9]+(\.[0-9]{1,2}){0,1}/
My thinking was that by using parenthesis like so: (\.[0-9]{1,2}), I would be able to bundle the whole "decimal plus one or two integers" part. But it isn't happening. Among other problems, this regex is allowing stuff like 245. and 345.567 to slip through. :(
Help, please!
Your regular expression is good, but you need to match the beginning and end of the string. Otherwise, your regex can match only a portion of the string and still (correctly) return a match. To match the beginning of the string, use ^, for the end, use $.
Update: as Avinash has noted, you can replace {0,1} with ?. JS supports \d for digits, so the regex can be further simplified
Finally, since if are only testing against a regex, you can use a non-capturing group ( (?:...) instead of (...)), which offers better performance.
original:
/[0-9]+(\.[0-9]{1,2}){0,1}/.test('345.567')
Fixed, and faster ;)
/^\d+(?:\.\d{1,2})?$/.test('345.567')

Allow only a single point in decimal numbers

How can I modify this regular expression to allow numbers with just one point?
/[^0-9\.]/g
It currently allows:
0
0.13
0.13.1 (this should not be allowable)
Your regex doesn't matches what you say it matches. You have used negation in character class, and that too without any quantifier. Currently it would match any non-digit character other than ..
For your requirement, you can use this regex:
/^\d+(\.\d+)?$/
Make the match a positive one:
/^\d*(\.\d+)?$/
Any number of digits, optionally followed by a point and at least one digit. But it’s not worth it to keep a negative match.
If you want to disallow an empty string (which the original regular expression wouldn’t do), you could do this:
/^(?=.)\d*(\.\d+)?$/
But you could also just check for an empty string, which looks better anyways.
I guess this should do /^(\d*)\.{0,1}(\d){0,1}$/ OR /^(\d*)\.?(\d){0,1}$/
(\d*) Represents number of digits before decimal.
\. followed by {0,1} OR ? will make sure that there is only one dot.
(\d){0,1} Allows only one digit after decimal.
You can try the following regex ^[-+]?\d*.?\d*$
Try,
(value.match(/^\d+([.]\d{0,1})?$/))
Try the following:
/^(\d*)(\.\d*)?$/g

PHP or Javascript - Find a specific string

Finding a specific string is relatively easy, but I am not sure where to begin on this one. I would need to extract a string that would be different every time, but with similar characteristics.
Here are some example strings I need to find in a paragraph, either at the beginning, end or somewhere in the middle.
7b.9t.7iv.4x
4ir.4i.5i.6t
7ix.7t.4t.0z
As you can see the string will always begin with a number, and would have up to 2 characters after it and will always contain 4 octets separated by dots.
Let me know if you may need more details.
EDIT:
Thanks to the answer below I came up with this, while not pretty, does what I need.
$body="test 1f.9t.7iv.4x test 1a.9a.7ab.4xa test ";
$var=preg_match_all("([0-9][a-z]{1,2}\.[0-9][a-z]{1,2}\.[0-9][a-z]{1,2}\.[0-9][a-z]{1,2})",$body,$matches);
$count=count($matches[0]);
$stack = array();
while($count > 0){
$count--;
array_push($stack, "<span id='ip_".$matches[0][$count]."'>".$matches[0][$count]."</span>");
}
$stack=array_reverse($stack);
$body=str_replace($matches[0],$stack,$body);
You can use a regular expression.
Something like this to get you started. There may be a better way to match since it's repeated, but....
([0-9][a-z]{1,2}\.[0-9][a-z]{1,2}\.[0-9][a-z]{1,2}\.[0-9][a-z]{1,2})
( Start a capture group
[0-9] match any character 0 through 9
[a-z] match any character [a-z]
{1,2} but only match the previous 1 or 2 times
\. match a literal . the \ is needed as an escape because . is a special character
) End capture group
Both php and javascript allow for regular expression use.
For an even better visual representation you can check out this tool: http://www.debuggex.com/
If you need each octet by itself (as a match) you can add more parenthesis () around each [0-9][a-z]{1,2} which will then store those octets individually.
Also note that \d is the same as [0-9] but I prefer the later as I find it a little more readable.

Using regexp to convert $(5.20) to -5.20

I'm trying to convert $(5.20) to -5.20 using regular expressions, but can't seem to figure out how to use regular expressions. Could someone please help me to resolve this issue? I need to remove the dollar sign and only accept digits with a maximum of 1 decimal point ie do not accept 5.2.0, but only 5.20. Also, the $ at the beginning is optional and there could be multiple $ as well.
Example of what I started with:
^\((\d)*\)$ - does not work
-$1
Try this regex
^\$\((\d+\.\d+)\)$
Your replacement should already be fine. This regex expects at least one digit before and after the decimal point.
The problem with your regex is, that it will only match if there is no decimal point at all. Also you don't check for the $ character. And lastly, if this $(5.20) is not your full string, than you should leave out the anchors at the beginning and at the end:
\$\((\d+\.\d+)\)
If you want to match numbers without decimal points, too, then you can make the dot and the second repetition optional:
\$*?\((\d+\.?\d*)\)

Categories