Understanding a regex expression - java

This expression evaluates a string to see if every character is a digit. I don't understand the -?. I know that ? means once or no times, but I'm not sure what putting dash in front of it means.
-?\d+

This is needed because an integer may be negative in which case it will start with a minus (-). So what you do here is to check for sequence of 1 or more digits optionally preceded by a single minus.

It is not a special character. The dash is there to allow negative numbers.

Related

Regex with no leading dot and maximum one leading zero

How can I write a regular expression that matches a string with the following properties?:
Contains numbers as well as only dot which is decimal separator (But dot is not necessary which means it can be 123 or 123.4 or 123.56).
No leading dot (Not .12).
Leading zero can be written only if it is followed by a dot (can not be like 000.12, only 0.12).
Have only 2 decimal places.
To the left of the decimal point you want a number (1 or more digits) that doesn't start with a zero:
[1-9][0-9]*
Or it can be just a zero:
0|[1-9][0-9]*
The value may have a decimal point and 1-2 digits after the decimal point:
\.[0-9]{1,2}
Left side is required. Decimal point and fractional digits are optional:
(?:0|[1-9][0-9]*)(?:\.[0-9]{1,2})?
The first non-capturing group is needed to limit the scope of the | pattern. The second non-capturing group is needed to make combined "decimal point and fractional digit" pattern optional.
Note that this will allow trailing zeroes, e.g. 100.00
Depending on preference, [0-9] can also be written as \d. I'd normally use \d, but since regex also has [1-9], I liked [0-9] better here as I felt it helped clarify the difference.
Depending on how regex is used, you may need to add the ^ begin / $ end anchors. They are needed when using find(), and are not needed when using matches() but don't hurt:
^(?:0|[1-9][0-9]*)(?:\.[0-9]{1,2})?$
Using negative look-ahead to ensure the string doesn't start with zero and another digit (but can be just zero, or zero followed by a dot)
^(?!0\d)\d+(?:\.\d{1,2})?$
Explanation and sample: https://regex101.com/r/7ymqcn/1
P.S. Also more efficient than Andreas' answer (takes fewer steps to match)
You could try converting the input string to float (that would take care of removing leading zeros and the dot without zero, as well adding ".00" if the input is only an integer, and you can set the maximum decimal numbers. If an exception is thrown at the conversion, the input doesn't match what you want. You can then convert the float back to string or keep it as a float value for calculation.
See:
https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#valueOf(java.lang.String)

Java regex - First needs to be the letter X(case insensitve) the rest digits

I need to match to see if a string is in the format of X[d].... It has to have the letter X (case intensive) at the start and AT LEAST 1 digit after. I tried the following regex, but it doesn't matchanything:
^(?i)[x](?=.*[0-9])*$
// ^(?i)[x] - first character needs to be x (case intensive)
// (?=.*[0-9]) - should have at least one digit after and must be all digits after
Use the following.
^(?i)x\d+$
This translates to case insensitive x followed by one or more digits 0-9. There's no need for brackets around the x because it's not a set. It's only one character.
Alternatively, you can create a set that consists of upper and lower case x.
^[xX]\d+$
In Java, you may use
s.matches("(?i)x[0-9]+")
It will match a string starting with x or X and then having 1 or more digits.
You should not quantify a lookahead, a zero-width assertion, since it would mean it would match an empty location and matching it repeatedly means you are still there and the regex index is not advanced.
However, Java regex just ignores a quantified lookahead. Your current regex, ^(?i)[x](?=.*[0-9])*$, matches x but not x5 as there is only one part to match, [x]. see the Java demo.
Even if you remove the * quantifier, ^(?i)[x](?=.*[0-9])$ does not match any string since $, end of string, is required right after x while (?=.*[0-9]) positive lookahead requires a digit after any 0+ chars other than line break chars.

Java Regular Expressions "\\d[a-zA-z]?"

I have this regular expression in Java : \\d[a-zA-z] ?
It should only allow letters followed by 1 or 0 character.
However when I match it with, for example, 17c or even 21, it does not result in a match. This is the code I use:
if (!(pattern.matches("\\d[a-zA-z]?"))) {
Throw error...;
}
Thanks for any help!
Well that's because 17c and 21 don't match "\d[a-zA-z]?". This expression matches one digit followed by a character.
Try to use "\d+[a-zA-z]*" which matches one or more digits followed by zero or more characters.
It should only allow letters followed by 1 or 0 character.
Try with this regex:
[a-zA-Z]+.?
Here:
[a-zA-Z]+ matches at least one letter (upper and lower case)
.? matches any character (except newline) zero or one times.
possibility \d+[a-zA-Z]? the one you are looking

Check if String ends with two digits after a dot in Regular Expression?

I'm trying to test if a String ends with EXACTLY two digits after a dot in Java using a Regular Expression. How can achieve this?
Something like "500.23" should return true, while "50.3" or "50" should return false.
I tried things like "500.00".matches("/^[0-9]{2}$/") but it returns false.
Here is a RegEx that might help you:
^\d+\.\d{2,2}$
it may neither be perfect nor the most efficient, but it should lead you in the right direction.
^ says that the expression should start here
\d looks for any digit
+ says, that the leading \d can appear as often as necessary (1–infinity)
\. means you are expecting a dot(.) at one point
\d{2,2} thats the trick: it says you want 2 and exactly 2 digits (not less not more)
$ tells you that the expression ends there (after the 2 digits)
in Java the \ needs to be escaped so it would be:
^\\d*\\.\\d{2,2}$
Edit
if you don't need digits before the dot (.) or if you really don't care what comes before the dot, then you can replace the first \d+ by a .* as in Bohemians answer. The (non escaped) dot means that the expression can contain any character (not only digets). Then even the leading ^ might no longer be necessary.
\\.*\\.\\d{2,2}$
use this regex
String s="987234.42";
if(Pattern.matches("^\\d+(\\.\\d{2})$", s)){ // string must start with digit followed by .(dot) then exactly two digit.
....
}
Firstly, forward slashes are no part of regular expressions whatsoever. They are however used by some languages to delimit regular expressions - but not java, so don't use them.
Secondly, in java matches() must match the whole string to return true (so ^ and $ are implied in the regex).
Try this:
if (str.matches(".*\\.\\d\\d"))
// it ends with dot then 2 digits
Note that in java a bash slash in a regex requires escaping by a further back slash in a string literal.

Require Help for Regular Expression

I am Doing a Check on the JTextfield Values that it Should be XX.YY.Z format
10.01.5
No space at beginning or after allowed.
EDIT:-
How Can I Specify Last as Alphanumeric character i.e. Z can be Number or character
\d matches a digit, and \. matches a dot.
\d\d\.\d\d\.\d
i.e. "\\d\\d\\.\\d\\d\\.\\d".
I don't have much experience in Java but this what I would do in PHP.
^\d\d.\d\d.\d$
\d represents one degit, \d\d represents two degits
^ a caret character is there to ensure that it must start with the number (No spaces at the beginning)
$ a dollar sign ensures that there will be no spaces or other characters at the end.
You could use quantifiers
\d{2}\.\d{2}\.\d
That is the indicated, and your regex becomes more easy to read and to change.
more on Quantifiers

Categories

Resources