Is there a way to use a Java regex to change a String to be of a certain format? For example, I have an input String containing a date & time which can be input with a variety of delimiters, can I use a regex to change it to use a specific delimiter? If I can, how can I do it? Currently I'm just checking the input with a regex and then concatenating a new String together with the desired delimiters like so:
Pattern dtPatt = Pattern.compile("\\d\\d\\d\\d[/\\-.]\\d\\d[/\\-.]\\d\\d[tT/\\-.]\\d\\d[:.]\\d\\d[:.]\\d\\d");
Matcher m = dtPatt.matcher(dtIn);
if (m.matches()) {
String dtOut = dtIn.substring(0, 4) + "/" + dtIn.substring(5, 7) + "/" +
dtIn.substring(8, 10) + "-" + dtIn.substring(11, 13) + ":" +
dtIn.substring(14, 16) + ":" + dtIn.substring(17, 19);
// do process开发者_如何学编程ing with dtOut
} else {
System.out.println("Error! Bad date/time entry.");
}
It seems like I should be able to do this with a regex, but a lot of googling, reading, and experimentation has not yielded anything that works.
Try the following
Pattern dtPatt = Pattern.compile( "(\\d\\d\\d\\d)[/\\-.](\\d\\d)[/\\-.](\\d\\d)[tT/\\-.](\\d\\d)[:.](\\d\\d)[:.](\\d\\d)" );
Matcher m = dtPatt.matcher( str );
if ( m.matches() )
{
StringBuffer sb = new StringBuffer();
m.appendReplacement( sb, "$1/$2/$3-$4:$5:$6" );
String result = sb.toString();
}
else
{
System.out.println( "Error! Bad date/time entry." );
}
Two changes
- Change the regex pattern to have groupings, using ()
- Use appendReplacement with a replace pattern where $x uses a specific group matched by the pattern.
I would try
DateFormat DF = new SimpleDateFormat("yyyy/MM/dd-HH:mm:dd");
String dtIn2 = String.format("%s/%s/%s-%s:%s:%s", dtIn.split("\\D+"));
DF.parse(dtIn2); // to validate the date produced.
Try Matcher's appendReplacement()
and appendTail()
methods. There is a good example in appendReplacement()
:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
精彩评论