How do you put the symbol in the regular expression java?
-
Good afternoon, I can't lead to a normal form of disparate with regular expression
"^\\s(\\d){2}(\\d){2}(\\d){2}\\s{2}(\\d){6}\\s{3}$"
The date and time of this kind is 09072016 154915, which is required to be obtained by means of a tax of 09-07-2016 15:49:15. Reading that symbols can be inserted in the sixteenth system as such
\x2D и \x3A
But it doesn't work. Repeat code supplemented by expressions
"^\\s(\\d){2}\\x2D(\\d){2}\\x2D(\\d){2}\\s{2}(\\d){2}\\x3A(\\d){2}\\x3A(\\d){2}\\s{3}$"
String variableName = fileName; Pattern pattern = Pattern.compile("^\\s(\\d){2}\\x2D(\\d){2}\\x2D(\\d){2}\\s{2}(\\d){2}\\x3A(\\d){2}\\x3A(\\d){2}\\s{3}$"); Matcher matcher = pattern.matcher(variableName);
while (matcher.find()) date = matcher.group(); System.out.println(date);
It doesn't work.
-
Problem is, you don't understand how the regexes work. Method
matcher.find()
Looking for regular expression on the line. Giving him what you want to put as a replacement is wrong in principle. We need to do a different way to replace it. For example:// где ищем: String s = "09072016 154915"; // что ищем: String rx = "(\\d{2})(\\d{2})(\\d{4})\\s+(\\d{2})(\\d{2})(\\d{2})"; Pattern pattern = Pattern.compile(rx); Matcher matcher = pattern.matcher(s); StringBuffer strbuf = new StringBuffer(); while (matcher.find()) { // на что меняем: matcher.appendReplacement(strbuf, "$1-$2-$3 $4:$5:$6"); } matcher.appendTail(strbuf); // Result: 09-07-2016 15:49:15 System.out.println("Result: " + strbuf.toString());