Regex + sign followed by numbers - java

Hi i want to find Strings like "+19" in Java
so a + sign followed by infinite amount of numbers.
How do i do this?
Tried "+[0123456789]"
and "\+[0123456789]"
thank you :)

This is the regex you want to use:
\\+\\d+
Two kinds of plus are being used here. The first is escaped with two backslashes because it is treated as a literal. The second one means match 1 of more times (i.e. match any digit one or more times).
Code:
String input = "+19";
if (input.matches("\\+\\d+")) {
System.out.println("input string matches");
}

Yes, to match a plus you need to escape it with two backslashes in a C string literal that Java uses. A literal plus needs to be either escaped or put into a character class, [+]. If you just use a plus symbol, it becomes a quantifier that matches the previous symbol or group one or more number of times.
Also, note that the \d shorthand digit class can match more than just ASCII digits if Pattern.UNICODE_CHARACTER_CLASS flag is passed to Pattern.compile (or embedded (?U) flag is added at the start of the pattern). It is advised to use unambiguous patterns in case the code might be maintained or enhanced/adjusted by different developers later.
Most people prefer patterns without escaping backslashes if possible since that allows to avoid issues like the one you faced.
Here is a version of the regex that does not require any escaping:
"[+][0-9]+"
Also, the plus quantifier does not match an infinite number of digits, only MAX_UINT number of times.

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.

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.

Regex Query in Java Program

^[0-9]\\d*(\\.\\d+)?$
I can't quite work out what the above regex pattern is looking for. I'm tempted to interpret it as "find anything that is not the numbers 0-9 inclusive, then find zero or more occurrences of a single digit, then find zero or one occurrences of a decimal point followed by at least one digit" but I'm not sure.
Part of my confusion stems from the fact that in the SCJP6 certification book, the not operator is included inside the square brackets, whereas here it's outside. Also, I am just generally inexperience when it comes to regex.
Can someone please help? [This is from a Java program. Is the above in any way Java specific?] Thanks.
^ start of a string
[0-9] a single digit
\\d* any amount of digits (0-infinity)
(\\.\\d+)? Once, or not at all: a dot followed by at least one digit
$ end of string.
You have a complicated regex that will match any floating point or non floiting point number.
Have a look at the java.util.Pattern class and and the Oracle Java Regex Tutorial.
It is looking a one or more digits, optionally followed by a . and one or more digits. It is confusing as it is needlessly complicated. It is the same as
^\\d+(\\.\\d+)?$
\d is defined as A digit: [0-9]
When the "^" operator is outside of a character class "[]" it denotes the start of input, "$" defines end of input.
So your description is correct, but it should be changed to:
find a single digit from zero to nine...
for more information about regular expressions check out this link

Regular expression to match a character only once before any whitespace

In Java, what regular expression would I use to match a string that has exactly one colon and makes sure that the colon appears before any whitespace?
For example, it should match these strings:
label: print "Enter input"
But: I still had the money.
ghjkdhfjkgjhalergfyujhrageyjdfghbg:
area:54
But not
label: print "Enter input:"
There was one more thing: I still had the money.
ghfdsjhgakjsdhfkjdsagfjkhadsjkhflgadsjklfglsd
area::54
If you use it with matches (which requires to match the entire string), you could use
[^\\s:]*:[^:]*
Which means: arbitrarily many non-whitespace, non-: characters, then a :, then more arbitrarily many non-: characters.
I've really only used two regex concepts: (negated) character classes and repetition.
If you want to require at least one character before or after :, replace the corresponding * with + (as jlordo pointed out in a comment).
The following should work:
^[^\s:]*:(?!.*:)
If your strings can contain line breaks, use the DOTALL flag or change the regex to the following:
(?s)^[^\s:]*:(?!.*:)
It depends on what we call white space, it could be
[^\\p{Space}:]*:[^:]
The following should get you started:
Matcher MatchedPattern = Pattern.compile("^(\\w+\\:{1}[\"\\w\\s\\.]*)$").matcher("yourstring");

How can I express such requirement using Java regular expression?

I need to check that a file contains some amounts that match a specific format:
between 1 and 15 characters (numbers or ",")
may contains at most one "," separator for decimals
must at least have one number before the separator
this amount is supposed to be in the middle of a string, bounded by alphabetical characters (but we have to exclude the malformed files).
I currently have this:
\d{1,15}(,\d{1,14})?
But it does not match with the requirement as I might catch up to 30 characters here.
Unfortunately, for some reasons that are too long to explain here, I cannot simply pick a substring or use any other java call. The match has to be in a single, java-compatible, regular expression.
^(?=.{1,15}$)\d+(,\d+)?$
^ start of the string
(?=.{1,15}$) positive lookahead to make sure that the total length of string is between 1 and 15
\d+ one or more digit(s)
(,\d+)? optionally followed by a comma and more digits
$ end of the string (not really required as we already checked for it in the lookahead).
You might have to escape backslashes for Java: ^(?=.{1,15}$)\\d+(,\\d+)?$
update: If you're looking for this in the middle of another string, use word boundaries \b instead of string boundaries (^ and $).
\b(?=[\d,]{1,15}\b)\d+(,\d+)?\b
For java:
"\\b(?=[\\d,]{1,15}\\b)\\d+(,\\d+)?\\b"
More readable version:
"\\b(?=[0-9,]{1,15}\\b)[0-9]+(,[0-9]+)?\\b"

Categories

Resources