Java regex to extract version - java

I am trying to write a Java regex to strip off Java version from string I get from java -version command.
If the string is java version 1.7.0_17 I need to extract 1.7 and 17 separately. Suppose if the string is java version 1.06_18 I need to extract 1.06 and 18. Where first string should be only till the first decimal point. I tried with the below regex:
Pattern p = Pattern.compile(".*\"(.+)_(.+)\"");
But it extracts only 1.7.0 and 17, but I not sure how to stop still one decimal point.

For the test cases you give, you could use this : (\d+\.\d+).*_(\d+)

Re-read your question, my old answer didn't cover stopping at the first decimal point.
This should solve your problem:
Pattern p = Pattern.compile(".*?(\\d+[.]\\d+).*?_(\\d+)");
Tested:
String input = "java version 1.7.0_17";
Pattern pattern = Pattern.compile(".*?(\\d+[.]\\d+).*?_(\\d+)");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
String version = matcher.group(1); // 1.7
String update = matcher.group(2); // 17
}
Old version:
Instead of finding the numbers, I'd get rid of the rest:
String string = "java version 1.7.0_17";
String[] parts = string.split("[\\p{Alpha}\\s_]+", -1);
String version = parts[1]; // 1.7.0
String update = parts[2]; // 17

Related

StringUtils or any library class method to preserve the delimiter [duplicate]

This question already has answers here:
How to split a string, but also keep the delimiters?
(24 answers)
Closed 6 years ago.
I am having a string "role1#role2#role3#role4$arole" separated with delimiter # and $. I used below java code
String str = "role1#role2#role3#role4$arole";
String[] values = StringUtils.splitPreserveAllTokens(str, "\\#\\$");
for (String value : values) {
System.out.println(value);
}
And got the result
role1
role2
role3
role4
arole
But my requirement is to preserve the delimiter in the result. So, the result has to be as per requirement
role1
#role2
#role3
#role4
$arole
I analyzed the apache commons StringUtils method to do that but was unable to found any clue.
Any library class to get the above intended results?
You may use a simple split with a positive lookahead:
String str = "role1#role2#role3#role4$arole";
String[] res = str.split("(?=[#$])");
System.out.println(Arrays.toString(res));
// => [role1, #role2, #role3, #role4, $arole]
See the Java demo
The (?=[#$]) regex matches any location in a string that is followed with a # or $ symbol (note the $ does not have to be escaped inside a [...] character class).

Match path string using glob in Java

I have following string as a glob rule:
**/*.txt
And test data:
/foo/bar.txt
/foo/buz.jpg
/foo/oof/text.txt
Is it possible to use glob rule (without converting glob to regex) to match test data and return valud entries ?
One requirement: Java 1.6
If you have Java 7 can use FileSystem.getPathMatcher:
final PathMatcher matcher = FileSystem.getPathMatcher("glob:**/*.txt");
This will require converting your strings into instances of Path:
final Path myPath = Paths.get("/foo/bar.txt");
For earlier versions of Java you might get some mileage out of Apache Commons' WildcardFileFilter. You could also try and steal some code from Spring's AntPathMatcher - that's very close to the glob-to-regex approach though.
FileSystem#getPathMatcher(String) is an abstract method, you cannot use it directly. You need to do get a FileSystem instance first, e.g. the default one:
PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
Some examples:
// file path
PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
m.matches(Paths.get("/foo/bar.txt")); // true
m.matches(Paths.get("/foo/bar.txt").getFileName()); // false
// file name only
PathMatcher n = FileSystems.getDefault().getPathMatcher("glob:*.txt");
n.matches(Paths.get("/foo/bar.txt")); // false
n.matches(Paths.get("/foo/bar.txt").getFileName()); // true
To add to the previous answer: org.apache.commons.io.FilenameUtils.wildcardMatch(filename, wildcardMatcher)
from Apache commons-lang library.

Regular expression in Java and in Eclipse?

I want to remove all empty linse in Java. In Eclipse I will use:
\n( *)\n (or "\r\n( *)\r\n" in Windows)
. But in Java it isn't work (I used:
str=str.replaceAll("\n( *)\n")
). How to do it in Java using replaceAll? Sample:
package example
○○○○
public ... (where ○ is space)
I would do it like this
java.util.regex.Pattern ws = Pattern.compile("[\r|\n][\\s]*[\r|\n]");
java.util.regex.Matcher matcher = ws.matcher(str);
str = matcher.replaceAll(" ");

DecimalFormat not working on Windows 7, but working on Windows 8

I have an applet which is working fine on Windows 8, but on Windows 7 I get the following error:
Exception in thread "Thread-13" java.lang.NumberFormatException: For input string: "-0,9"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Float.parseFloat(Unknown Source)
at Tanc.Game$Corp.getDW(Game.java:1505)
at Tanc.Game.borders(Game.java:975)
at Tanc.Game.loose(Game.java:1068)
at Tanc.Game.gameLoop(Game.java:242)
at Tanc.Game$1.run(Game.java:144)
I have to mention that I tried on 2 different computers but the same problem. On Windows 8 I don't get this error...
And code
String zz = new DecimalFormat("#.##").format(corp400.y);
System.out.println(zz);
if (Float.parseFloat(zz) == 0.2f)
sw = true;
if (Float.parseFloat(zz) == -0.24f)
sw = false;code here
Probably problem with locale: on the computer with Win8 there are locale, where , means decimal separator, but on the other tested computers . means decimal separator.
I replaced DecimalFormat with (Math.round(corp400.y*100.0)/100.0)
But if anyone can find out how to fix DecimalFormat to work with Windows 8 and windows 7 please Comment/Answer.
Probably on windows 8 (where it works) you are using an English locale.
The problem, tough, is in the code:
String zz = new DecimalFormat("#.##").format(corp400.y);
actually uses the default locale to format corp400.y, but the JavaDoc says that Float.parseFloat
Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.
This means that, since Float.valueOf parses a floating point literal, it expects decimals separated by . not ,
The correct way to reverse your locale-dependant formatting is:
float value = new DecimalFormat("#.##").parse(zz).floatValue();
Alternatively, you could use the locale-independent formatting on both ways as in:
String zz = String.valueOf(corp400.y);
float value = Float.parseFloat(zz)

VBScript: Error with regex matching incorrect registry values

I am trying to match a Java version in HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall by iterating over the subkeys within Uninstall. I am trying to match a regular expression to Java 7 Update 40, but the regex is matching all DisplayName entries. Below is the code:
On Error Resume Next
Const HKEY_LOCAL_MACHINE = &H80000002
Dim oReg
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\.\root\default:StdRegProv")
Dim sPath, aSub, sKey
Set objRegEx = New RegExp
objRegEx.Pattern = "\w{4}\s\d{1}\s\w{6}\s\d+"
objRedEx.IgnoreCase = True
objRegEx.Global = False
sPath = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, aSub
For Each sKey In aSub
disName = "HKLM" & "\" & sPath & "\" & sKey & "\DisplayName"
unString = "HKLM" & "\" & sPath & "\" & sKey & "\UninstallString"
reDisName = objShell.RegRead(disName)
reUnString = objShell.RegRead(unString)
'Wscript.echo(reDisName)
If objRexEx.Test( reDisName ) Then
Wscript.echo "Match"
End If
'Wscript.echo ObjShell.RegRead(disName)
'Wscript.echo ObjShell.RegRead(unString)
Next
Sorry if the formatting is off, I put a ctrl-k in front of each code line. This is my first time posting here so go easy...
You should start all your scripts with Option Explicit and Dim all your variables. Then you wouldn't need sln's eagle eyes to spot your typo:
Option Explicit
Dim objRegEx : Set objRegEx = New RegExp
objRegEx.Pattern = "\w{4}\s\d{1}\s\w{6}\s\d+"
objRedEx.IgnoreCase = True
output:
cscript 19188400.vbs
...\19188400.vbs(4, 1) Microsoft VBScript runtime error: Variable is undefined: 'objRedEx'
If you insist on using a global On Error Resume Next (a most dangerous mal-practice) then you should disable it until your script is thoroughly debugged. Keeping the OERN in a script known to have even the slightest problem is inviting desaster. Asking for help with code containing a global OERN is futile. So run you program without the OERN and see if the cause for its misbehaviour in't obvious.
Diagnostic output should be as specific as possible. Your WScript.Echo "Match" just shows that the statement is executed; a WScript.Echo "Match", disname would be a bit better. Using .Execute and looking at the Match's details could be more revealing.
The .Pattern should be more specific to. If you look for java updates, anchoring a literal "java" at the start of the string, and asking for "upgrade" instead of "\w{6}" may help to avoid false positives. OTOH, my display names don't look like
Java 7 Update 19
but like
Java(TM) 6 Update 19
and who knows what the next owner of Java will put into the display name.
You seem to have a few typo's
objRedEx.IgnoreCase = True
...
If objRexEx.Test( reDisName ) Then

Categories

Resources