I have written the following Java code:
public void test(final String myString){
final String rule = "^[A-Z]\\d{2}(\\.\\d){0,2}$";
final Pattern pattern = Pattern.compile(rule);
final Matcher matcher = pattern.matcher(myString);
if(!matcher.matches()){
System.out.println("Failure, the String" + myString + " is not valid!");
}
}
The Regular Expression should by valid the following String:
[character are required][number are required][number are required][point is optional][number is optional][number is optional]
It is important, that if a point was declared in the string, at least one Number must be followed!
My solution only works for Strings like J45 or J45.9
Java Java like these are allowed:
D99
M00.0
M01.6
J98.3
T05.0
M96.81
D68.20
Java Strings like these are not allowed:
9D.0
6G
7H.
M96.811
J234.82
G687.1
GU87.11
How I can solve this problem by using Regular Expressions in Java?
[point is optional][number is optional][number is optional]
You need to make the dot optional and set the {0,2} quantifier to the \d pattern only:
^[A-Z]\d{2}\.?\d{0,2}$
See the regex demo
Details:
^ - start of string anchor
[A-Z] - an uppercase ASCII letter
\d{2} - any 2 digits
\.? - an optional dot
\d{0,2} - any 0 to 2 digits
$ - end of string.
Since you are using .matches() that anchors the pattern by default, you may declare it without the ^ and $ anchors as
final String rule = "[A-Z]\\d{2}\\.?\\d{0,2}";
See an online Java test.
Or, if there must be 1 or 2 digits after a dot, or if no dot is present 0 to 2 digits are allowed, you may consider using
^[A-Z]\d{2}(?:\.\d{1,2}|\d{0,2})$
See this regex demo, and use as
final String rule = "[A-Z]\\d{2}(?:\\.\\d{1,2}|\\d{0,2})";
where (?:\\.\\d{1,2}|\\d{0,2}) matches either a . and then any 1 or 2 digits, OR any 0 to 2 digits.
This regex expression:
Requires one Uppercase Letter followed by 2 number digits
Followed by an optional combination of a point and 1-2 number digits
^[A-Z]\d{2}(?:\.\d{1,2})?$
Related
I only want Strings with a very specific format to be allowed in my methods.
The format is "Intx^Int". Here are some concrete examples:
"5x^2"
"-21x^5"
"14x^-12"
I tried the following code, but it doesn't seem to work correctly:
import java.util.regex.Pattern;
Pattern p = Pattern.compile("\\dx^\\d");
System.out.println(p.matcher("14x^-12").matches());
You only match a single digit (not whole numbers) without any sign in front (it seems you want to match optional - chars in front of the numbers). You also failed to escape the ^ char that is a special regex metacharacter denoting the start of a string (or line if Pattern.MULTILINE option is used).
You can use
Pattern p = Pattern.compile("-?\\d+x\\^-?\\d+");
System.out.println(p.matcher("14x^-12").matches());
The pattern matches
-? - an optional -
\d+ - one or more digits
x - an x
-\^ - a ^ char
-? - an optional -
\d+ - one or more digits
To support numbers with fractions, you might further tweak the regex:
Pattern p = Pattern.compile("-?\\d+(?:\\.\\d+)?x\\^-?\\d+(?:\\.\\d+)?");
Pattern p = Pattern.compile("-?\\d*\\.?\\d+x\\^-?\\d*\\.?\\d+");
Also, see Parsing scientific notation sensibly?.
I am trying to replace everything except a specific expression including digits in java using only the replaceAll() method and a single regex.
Given the String P=32 N=5 M=2 I want to extract each variable independently.
I can match the expression N=5 with the regex N=\d, but I can't seem to find an inverse expression that will match anything but N=\d, where x may be any digit.
I do not want to use Pattern or Matcher but solve this using regex only. So for x, y, z being any digit, I want to be able to replace everything but the expression N=y in a String P=x N=y M=z:
String input = "P=32 N=5 M=2";
output = input.replaceAll(regex, "");
System.out.println(output);
// expected "N=5"
You may use
s = s.replaceAll("\\s*\\b(?!N=\\d)\\w+=\\d+", "").trim();
See the Java demo and the regex demo.
Details
\s* - 0+ whitespaces
\b - a word boundary
(?!N=\d) - immediately to the right, there should be no N= and any digit
\w+ - 1+ letters/digits/_
= - an = sign
\d+ - 1+ digits.
How can i change 4 -1/4 -5 to 4/1 -1/4 -5/1 using regex?
String str = "4 -1/4 -5";
String regex = "(-?\\d+/\\d+)";
Matcher matcher = Pattern.compile(regex).matcher(str);
My code finding only fraction but i want to find integer without fraction.
String result = str.replaceAll("(?<!/)\\b\\d+\\b(?!/)", "$0/1");
looks for entire numbers (\b\d+\b), not preceded by ((?<!/)) nor followed by a slash ((?!/)), and adds /1 to them.
Try (?<=-| |^)(\d+)(?!\d*\/)
Explanation:
(?<=...) - positive lookahead, assert, what precedes matches pattern inside
-| |^ - match either -, , or beginning of a line ^
(\d+) - match one or more digits and store in first capturing group
(?!\d*\/) - negative lookahead, assert what follows is not zero or mroe digits followed by \/.
Replace it with \1/1, so first capturing group followed by /1
Demo
I'm not sure I understand what you want to do here, but if you want to remove the slashes you can use:
str.replaceAll("\\/", " ");
This will leave you with a string having only the integers.
I'm dealing with regular expressions, but I’m not a big fan of it and I’m obliged to deal with it in my task :(
I have passed hours looking for a solution but everytime I fail to cover all scenarios.
I have to write a regular expression template that supports these patterns:
DYYU-tx-6.7.9.7_6.1.1.0
DYYU-tx-6.7.9.7_60.11.11.09
DYYU-tx-60.70.90.70_6.1.1.0
I feel that this is very simple to do.. So excuse me if it's a stupid question for someone :(
I tried this pattern but it didn’t work :
^.*_.*-.*-([0-9]*)\\..*\\..* $
Any help please.
I will be more than thankful.
There are many patterns in the samples that we can use to design expressions. For instance, we can start with this expression:
^[^-]+-[^-]+-[^_]+_([0-9]+\.){3}[0-9]+$
The expression is explained on the top right panel of this demo, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs step by step, if you like.
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "^[^-]+-[^-]+-[^_]+_([0-9]+\\.){3}[0-9]+$";
final String string = "DYYU-tx-6.7.9.7_6.1.1.0\n"
+ "DYYU-tx-6.7.9.7_60.11.11.09\n"
+ "DYYU-tx-60.70.90.70_6.1.1.0";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
RegEx Circuit
jex.im visualizes regular expressions:
Try this one:
^\w+-\w+-(\d+)(\.\d+)+_(\d+\.)+\d+
Demo
In Java most probably sth like this:
"^\\w+-\\w+-(\\d+)(\\.\\d+)+_(\\d+\\.)+\d+"
Explanation:
^\w+-\w+- first two parts, e.g. DYYU-tx-
(\d+)(\.\d+)+_ numbers separated with . ending with _, e.g. 6.7.9.7_
(\d+\.)+\d+ numbers separted with ., e.g. 60.11.11.09
Your pattern does not match because you use .* which will first match until the end of the string. Then you match an _ so it backtracks to the last underscore and try to match the rest of the pattern.
Since there is 1 underscore, you want to match a hyphen that comes after it, but there is no hyphen to match after the underscore so there is no match.
Another way to write it could be using a negated character class [^-] matching not a hyphen instead of using .*
^[^-]+-[^-]+-\d+(?:\.\d+){3}_\d+(?:\.\d+){3} $
Explanation
^ Start of string
[^-]+- Match 1+ times any char other than -
[^-]+- Same as above
\d+(?:\.\d+){3} Math 1+ digits, repeat 3 times matching a . and 1+ digits
_ Match underscore
\d+(?:\.\d+){3} Math 1+ digits, repeat 3 times matching a . and 1+ digits
[ ]$ Match a space (denoted between brackers for clarity) and assert end of string
In Java
String regex = "^[^-]+-[^-]+-\\d+(?:\\.\\d+){3}_\\d+(?:\\.\\d+){3} $";
Regex demo
Note that in your example data, the strings end with a space, and so there is a space before $
DYYU-tx-(?>\d+[._]?){8}
Search for the literal DYYU-tx-
Look for 1 or more digits that may be followed by a . or an _ 8 times.
I assumed that it would always start with DYYU-tx- and that it would always be 4 numbers separated by periods followed by an underscore which would then have 4 more numbers separated by periods.
I have the following regex but it fails (the inner digits with the points) :
([0-9]{1,3}\.?[0-9]{1,3}\.?[0-9]{1,3})
I want that it covers the following cases:
123 valid
123.4 valid
123.44 valid
123.445 valid
123.33.3 not ok (regex validates it as true)
123.3.3 not ok (regex validates it as true)
123.333.3 valid
123.333.34 valid
123.333.344 valid
Can you please help me?
You have multiple case, I would like to use | the or operator like this :
^([0-9]{1,3}|[0-9]{1,3}\.[0-9]{1,3}|[0-9]{1,3}\.[0-9]{3}\.[0-9]{1,3})$
^ ^ ^ ^
you can check the regex demo
details
The regex match three cases :
case 1
[0-9]{1,3}
this will match one or more digit
case 2
[0-9]{1,3}\.[0-9]{1,3}
this will match one or more digit followed by a dot then one or more digits
case 3
[0-9]{1,3}\.[0-9]{3}\.[0-9]{1,3}
this will match one or more digit followed by a dot then three digits then a dot then one or three digits
Note you can replace [0-9] with just \d your regex can be :
^(\d{1,3}|\d{1,3}\.\d{1,3}|\d{1,3}\.\d{3}\.\d{1,3})$
How about this one (demo at Regex101). It's pretty short and straightforward Regex:
(^\d{3}\.\d{3}\.\d{1,3}$)|(^\d{3}\.\d{1,3}$)|(^\d{3}$)
This recognizes three valid separate groups.
(^\d{3}\.\d{3}\.\d{1,3}$) as a group which must have 3 digits, a dot, 3 more digits, a dot and 1-3 digits.
(^\d{3}\.\d{1,3}$) as a group which must have 3 digits, a dot and 1-3 digits.
(^\d{3}$) as a group which must have 1-3 digits.
These groups split with the or (|) statement.
However, since you have tagged java, why don't let Java to take some responsibility and help Regex where isn't strong? I would rather match the format ((?:\d{1,3}\.?)+) and check programmatically whether the count of numbers is valid.
Use the following expression with .matches:
s.matches("\\d{1,3}(?:\\.\\d{3})?(?:\\.\\d{1,3})?")
See the regex demo
Details
^ - implicit, not necessary as the pattern is used in .matches that requires a full string match
\d{1,3} - 1 to 3 digits
(?:\.\d{3})? - an optional . and 3 digits
(?:\.\d{1,3})? - an optional sequence of . and 1 to 3 digits
$ - implicit, not necessary since the pattern is used in .matches that requires a full string match