Regex Query in Java Program - java

^[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

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.

Regex + sign followed by numbers

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.

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.

Java Regex - What does each of these parts do?

if(password.matches("(?=.*[0-9].*[0-9])(\\w{8,})") )
System.out.println("Valid Password");
else
System.out.println("Invalid Password");
I am checking a password to ensure it has at least 8 characters in length, which can be letters or digits and it must have at least 2 digits. This appears to work for me but I just wanted to confirm I was doing this right. Also, I have been trying to research and figure out exactly what each piece is doing. Below is what I believe each piece to be doing, but if I am incorrect, would you please explain what the particular portion is actually doing. Thanks
?= tells the program to remember if the digits [0-9] which I am looking for are found ?
.* says for any number of [0-9]?
[0-9] Specifies any number from 0-9.
.*[0-9] Then the regex looks for another number from 0-9 ?
(\\w{8,}) looks for any letters (uppercase or lowercase) and digits, with a minimum length of 8 characters?
That regex has two main parts:
(?=.*[0-9].*[0-9])
(\\w{8,})
Part 1. is a positive look ahead, which has the form (?=pattern). "Look arounds" (positive/negative look behinds/aheads) assert, without consuming (or capturing), that the adjacent input matches a certain pattern. In this case, it's asserting that the input following the current point contains (at least) 2 digits (.* meaning 0-n chars, [0-9] meaning any number character). Incidentally, it could be expressed more succinctly as (?=(.*[0-9]){2}
Part 2. means "at least 8 word characters" - a word character is any letter, any number or an underscore. The brackets around it (unnecessarily) capture the 8+ word characters as group 1
?= is a positive look ahead, That means that it is searching for something ahead of it.
http://www.regular-expressions.info/lookaround.html
For more info on the look ahead.
http://rubular.com/
Great for testing out any regex.

Add an identifier when a space is followed by four digits

I am dealing with a String,
30-Nov-2012 30-Nov-2012 United Kingdom, 31-Oct-2012 31-Oct-2012 United Arab Emirates, 29-Oct-2012 31-Oct-2012 India
I need to add spaces every time a space appears after a four digit numbers, i.e.:
30-Nov-2012#30-Nov-2012#United Kingdom, 31-Oct-2012#31-Oct-2012#United Arab Emirates, 29-Oct-2012#31-Oct-2012#India
I don't know how to write Regular Expressions, any help please?
Since you don't know how to write Regular Expressions, your best bet is learning how to use Regular Expressions.
Here's a pretty good tutorial.
http://www.vogella.com/articles/JavaRegularExpressions/article.html
The expression you want to write doesn't seem very complicated. You should be able to do it after going through this tutorial.
Edit: Here's another hint. Take a look at replaceAll
and also take a look at positive lookbehinds
Edit2: I'm bored, so here's the answer.
string.replaceAll("(?<=\\d{4})\\s", "#");
Try this regex:
(\d{4})\s+
replace with
$1#
and a sample code:
String result = inputString.replaceAll("(\\d{4})\\s+", "$1#");
explain:
\d
Matches any decimal digit.
{n}
Matches the previous element exactly n times.
\s
Matches any white-space character.
+
Matches the previous element one or more times.
(subexpression)
Captures the matched subexpression and assigns it a zero-based ordinal number.
$ number
Substitutes the substring matched by group number.

Categories

Resources