Java Regular Expression to match dollar amounts - java

This is what i've been using
\$?[0-9]+\.*[0-9]*
But when i was doing some testing i noticed that things like
$$$34.00
would return as a match (but matcher.group()) just returns the matched substring. I don't want it to even pass the regular expression if the user enters more than one dollar sign so i tried this:
\${1}[0-9]+\.*[0-9]*
but this seems to behave the same as the regular expression i first typed. Right now i'm testing this in java but, i plan to use it in c++ using the Boost libraries. But Please don't give me that solution here because i'm trying to learn without someone giving me the answer.
But i do need help making it so the user can only enter one dollar sign (which is what i thought \${1} would do)

I would suggest avoiding the use of regular expressions for currency parsing, esp when Java provides you much simpler ways to solve this problem.
Consider this code:
String str = "$789.11"; // user entered value
Number number = null;
try {
number = NumberFormat.getCurrencyInstance(Locale.US).parse(str);
} catch(ParseException pe) {
// ignore
}
if (number != null) {
// proceed as user entered a good value
}
else {
// user didn't enter a good value
}

Since you're doing this to learn regex...
^\$(([1-9]\d{0,2}(,\d{3})*)|(([1-9]\d*)?\d))(\.\d\d)?$
Breakdown:
^\$ start of string with $ a single dollar sign
([1-9]\d{0,2}(,\d{3})*) 1-3 digits where the first digit is not a 0, followed by 0 or more occurrences of a comma with 3 digits
or
(([1-9]\d*)?\d) 1 or more digits where the first digit can be 0 only if it's the only digit
(\.\d\d)?$ with a period and 2 digits optionally at the end of the string
Matches:
$4,098.09
$4098.09
$0.35
$0
$380
Does not match:
$098.09
$0.9
$10,98.09
$10,980456

You can do something like [^\$]*\$? in the beginning. This would insure that there are no duplicate $ signs, but also matches if there is no $ present.
Also, if you are working with currency (possible decimal and 2 digits after), you should use [\.\d{2}]?.
This says that it can be a match if it's followed by ONE instance of a period and 2 digits or nothing at all. As stated in the comments, it can also match multiple periods in a row, so you shouldn't use the * quantifier after \.

You are missing ^(beginning of string),$(end of string)
^\$\d+([.][0-9]+)?$

i know this is coming late but this seems to work for me
(\$)?[0-9]+\.*[0-9]*
i dont understand why it didnt work for you.

[$](([1-9]+\.?\d*)|([0]\.\d*)|[0]) pattern ideally for this case.
This is standard Perl regex but could be use in JAVA with some libs.

Related

Need regex for a string having characters followed by even number of digits

Can anyone tell how I can write regex for a string that take one or more alphanumeric character followed by an even number of digits?
Valid:
a11a1121
bbbb11a1121
Invalid:
a11a1
I have tried ^[a-zA-Z*20-9]*$ but it is always giving true.
Can you please help in this regard?
The regex that you have mentioned will search for any number of [either a-z, or A-Z or 2 or 0-9]
You can break down your requirement to groups and then handle it accordingly.
Like you require at least one character. so you start with ^([a-zA-Z]+)$
Then you need numbers in the multiple of 2. so you add ^([a-zA-Z]+(\d\d)+)$
Now you need any number of combination of these. So the exp becomes: ^([a-zA-Z]+(\d\d)+)*$
You can use online tools like regex101 for these purpose. The provided regex in action here
You can achieve it with this regexp: ^[a-z0-9]*[a-z]+([0-9]{2})*$
Explanation :
[a-z0-9]*[a-z]+: a string of at least one character terminated by a non digit one
([0-9]{2})*: an odd sequence of digits (0 or 2*n digits). If the even sequence cannot be null, use ([0-9]{2})+ instead.

My code with matches() is not working. Why is it not working?

I am trying to create a small program that reads a password and determines if it is a password you can use. I was using matches() to see if it has at least one letter (uppercase or lowercase) and one digit as well as be 6 characters long. I try to use matches like this:
if ( passwordLength >= 6
&& password.matches("[A-Za-z]")
&& password.matches("\\d")
) {
System.out.println("Valid Password.");
}
else {
System.out.println("Invalid Password.");
}
Im not sure what i am doing wrong. Please help.
matches function should try to match the whole string using the regex we gave. So instead of using two or more matches functions for condition checking, you may use a single one with a complex regex. And also it seems like your password would contain not only digits or letters but also some other characters too.
string.matches("^(?=.*[a-zA-Z])(?=.*\\d).{6,}$");
(?=.*[a-zA-Z]) Positive lookahead which asserts that the string going to be matched must contain atleast one letter.
(?=.*\\d) asserts it must contain atleast one digit.
.{6,} ensures that the length must be atleast 6 and atmost any..
For the length to be exactly 6 then change .{6,} in the above to .{6}
DEMO
It looks like you're misinterpreting the matches function, which matches over the entire input, while you're expecting it to return true if a substring matches. As others suggested, you'll need to use a single regex and matches() call since you're asking if the string is a single character AND a number (which would never be true).
Another important point, though it may not be important to you, is that a password should never be stored as a String object since they're immutable and can persist long enough for something else to come along and read it. More on that here.
There are a couple of things wrong with your code:
Your regex is wrong. You are only matching on 1 character, so you should change the [a-z] to [a-z]+.
You are matching on 'it should be bigger than 6, should be a character, AND it should be a number. That's different from your requirement.

String:matchs.method something not clear

Hi i was copying a code form the net,for a program but there where some isuees...
I understand everything , except this one ,please tell me everything about that...
".*\\d.*"
this is the hole code
public void checkS(String w){
this.w = w;
do{
if(w.matches(".*\\d.*")){
System.out.println("Contains a number,try again....(ya aint 2 Pac) ");
} else{
System.out.println("Allright "+">"+w+"<"+" lets go one and start the shit...");
runL=3;
}
}while(runL==2); }
and who do i write the thing between the [] for example if i want to search for :$"%&/ ?
Please give me a source to this topic i already search but didnt found something usefull
And if my english is bad pls Tell :D
The String.matches method performs a regular expression match. There are a number of good resources out there describing regular expressions. In this specific case ".*\\d.*" will match anything which contains at least 1 digit \d anywhere in the string.
The regular expression .*\\d.* does the following:
.*: Matches zero or more (*) of any character (.)
\\d: \d matches a number but you have to add an extra '\' because in java two back slashes (\\) becomes one. This is called escaping.
.*: same as mentioned previously
So all in all it will match any string that has zero or more characters one number then zero or more characters after that.
Some examples:
abasdfadsf7asdga
foo87980890bar
this is a str1ng that matches!
7

regex can't get special constructs (?=x) to work

I'm trying to get a valid regex to use in java (java.util.regex) that validates the following format:
a number that has max 15 digits, of which 3 MAX digits may be decimal which are preceeded by a separator (,)
So, valid would be:
123456789012345 (15 digits, ok)
12345678901234,1
[EDIT], these should also be valid:
1234567890123,45
123456789012,345
So far i've come up with the following regex pattern:
Pattern = [0-9]{1,15}(\,[0-9]{1,3})?
This checks for a a range of 1 to 15 digits, following by an optional separator followed by another 3 digits. However, this doesnt check the total length of the input. With this regex, a value of 123456789012345,123 would be valid.
So, i thought i'd add an extra expression that checks the total length, and use the "(?=" construct to simulate the logical AND behaviour.
So i started with adding that to my existing regex expression as follows:
Pattern = (?= [0-9]{1,15}(\,[0-9]{1,3})?)
This however results in basically everything i throw at it failing, and i cant get it to work further. I don't see what i'm doing wrong here? After this works, i'd add another expression to check total length, something like (?=.{16}) i think.
[EDIT]
Realised you wanted to accept total length of 16 if there is a ,, and also that you don't really need to use lookaround here, since you only have two cases. This works just fine:
public static boolean isValid(String input) {
return input.matches("^(\\d{0,15}|\\d{1,12},\\d{1,3})$");
}
This returns valid if one of these is true
input consists of 0-15 numbers or
input consists of 1-12 numbers, followed by a ,, followed by 1-3 numbers
[EDIT2]
Ok, new try:
public static boolean isValid(String input) {
return input.matches("^(\\d{0,15}|(?=.{3,16})\\d+,\\d{1,3})$");
}
This returns valid if one of these is true
input consists of 0-15 numbers or
input consists of 3-16 characters, consisting of at least one digit, followed by a ,, followed by 1-3 numbers
What about this one? play it on RegExr
\d{12,15},?\d{3}
this worked for me.
boolean a = Pattern.matches("\\d{15}|\\d{12},\\d{3}", "123456789012345");
System.out.println(a);//true
boolean b = Pattern.matches("\\d{15}|\\d{12},\\d{3}", "123456789012,345");
System.out.println(b);//true
boolean c = Pattern.matches("\\d{15}|\\d{12},\\d{3}", "1234567890123,456");
System.out.println(c);//false
so your regEx is:
\d{15}|\d{12},\d{3}
Try this regex:
^\d{1,12}(?:\d{0,3}|\d{0,2},\d|\d{0,1},\d\d|,\d\d\d)$

validating input string "RX-EZ12345678912345B" using regex

I need to validate input string which should be in the below format:
<2_upper_case_letters><"-"><2_upper_case_letters><14-digit number><1_uppercase_letter>
Ex: RX-EZ12345678912345B
I tried something like this ^[IN]-?[A-Z]{0,2}?\\d{0,14}[A-Z]{0,1} but its not giving the expected result.
Any help will be appreciated.
Thanks
Your biggest problem is the [IN] at the beginning, which matches only one letter, and only if it's I or N. If you want to match two of any letters, use [A-Z]{2}.
Once you fix that, your regex will still only match RX-E. That's because [A-Z]{0,2}? starts out trying to consume nothing, thanks to the reluctant quantifier, {0,2}?. Then \d{0,14} matches zero digits, and [A-Z]{0,1} greedily consumes the E.
If you want to match exactly 2 letters and 14 digits, use [A-Z]{2} and \d{14}. And since you're validating the string, you should end the regex with the end anchor, $. Result:
^[A-Z]{2}-[A-Z]{2}\d{14}[A-Z]$
...or, as a Java string literal:
"^[A-Z]{2}-[A-Z]{2}\\d{14}[A-Z]$"
As #nhahtdh observed, you don't really have to use the anchors if you're using Java's matches() method to apply the regex, but I recommend doing so anyway. It communicates your intent better, and it makes the regex portable, in case you have to use it in a different flavor/context.
EDIT: If the first two characters should be exactly IN, it would be
^IN-[A-Z]{2}\d{14}[A-Z]$
Simply translating your requirements into a java regex:
"^[A-Z]{2}-[A-Z]{2}\\d{14}[A-Z]$"
This will allow you to use:
if (!input.matches("^[A-Z]{2}-[A-Z]{2}\\d{14}[A-Z]$")) {
// do something because input is invalid
}
Not sure what you are trying to do at the beginning of your current regex.
"^[A-Z]{2}-[A-Z]{2}\\d{14}[A-Z]$"
The regex above will strictly match the input string as you specified. If you use matches function, ^ and $ may be omitted.
Since you want exact number of repetitions, you should specify it as {<number>} only. {<number>,<number>} is used for variable number of repetitions. And ? specify that the token before may or may not appear - if it must be there, then specifying ? is incorrect.
^[A-Z]{2}-[A-Z]{2}\\d{14}[A-Z]$
This should solve your purpose. You can confirm it from here
This should solve your problem. Check out the validity here
^[A-Z]{2}-[A-Z]{2}[0-9]{14}[A-Z]$
^([A-Z]{2,2}[-]{1,1}[A-Z]{2,2}[0-9]{14,14}[A-Z]{1,1}){1,1}$

Categories

Resources