I am trying to delimit the , and space my input is 21, May, 2012 my output should be 2012-May-21.
String s = args[0];
String[] s1 = s.split(",\\s+");
System.out.print(s1[2] + "-" + s1[1] + "-" + s1[0]);
It is working if I am writing for only , delimiter but getting ArrayIndexOutOfBoundsException when trying for space as delimiter.
Since both ,,space are optional as mentioned in the comment..
String[] s1 = s.split(",|\\s+");
Though I won't use regex to parse date
input=input.replaceAll("\\s*","");//remove any space if any
java.util.Date date= (new SimpleDateFormat("dd,MMM,yyyy")).parse(input);
String output=(new SimpleDateFormat("yyyy-MMM-dd")).format(date);
Try this,
String date = " 21 , May, 2012";
String[] s1 = date.split(",\\s*");
System.out.println(s1[2].trim() + "-" + s1[1].trim() + "-" + s1[0].trim());
You can also do this using String#replaceAll :
s.replaceAll(",\\s*", "-");
Related
If I have a string like :
String str = "startDate:23/04/2016;endDate:;renewDate;"
Required multiple operation on the string.I need to get a String and extract different sub-strings using a delimiter (";") then again extract different sub-strings to form a key-value using a delimiter (":"). If against the key their is no value present the update with diff-diff default value like ("01/01/2000","01/01/1900" since both are of type Date).
if you notice for renewDate field their is no separator (":") in this case we need to append the separator along with default value (:01/01/1900) so that my expected result would be like :
String str = "startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;"
I have tried below regex but it is not working for all scenario :
String regExpression = "(?<=\\bendDate:)[;]+"
str = str.replaceAll(regExpression , "01/01/2000");
Can any one guide me how to achive the result using regex.Thanks!!!!!
As Tim said we can use regex pattern to replace the value. Adding to his answer, the only change I recommend to add colon(:) as optional in pattern used for both renewDate and endDate in text.
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate;";
str = str.replaceAll(";endDate:?;", ";endDate:"+endDate+";");
str = str.replaceAll(";renewDate:?;", ";renewDate:"+renewDate+";");
System.out.println(str);
This will give the output as below
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
Using a regex replacement, we can try:
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate:;";
String output = str.replaceAll("\\bendDate:;", "endDate:" + endDate + ";")
.replaceAll("\\brenewDate:;", "renewDate:" + renewDate + ";");
System.out.println(output);
This prints:
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
The logic here is to only target empty end and renew date fields, including default values if needed.
Alternatively, separate strings based on your first delimiter ; and then :.
String str = "startDate:23/04/2016;endDate:;renewDate;";
String dates[] = str.split(";");
for(String date : dates){
String default[] = date.split(":");
output.append(default[0] + ":" + (default.length > 1 ? default[1] : defaultDate));
}
I have a class that parses ZonedDateTime objects using.split() to get rid of all the extra information I don't want.
My Question: Is there a way to use square brackets as delimiters that I am missing, OR how do I get the time zone ([US/Mountain]) by itself without using square brackets as delimiters?
I want the String timeZone to look like "US/Mountian" or "[US/Mountian]
What I've Tried:
Ive tried wholeThing.split("[[-T:.]]?) and wholeThing.split("[%[-T:.%]]") but those both give me 00[US/Mountain]
I've also tried wholeThing.split("[\\[-T:.\\]]) and wholeThing.split("[\[-T:.\]") but those just give me errors.
(part of) My Code:
//We start out with something like 2016-09-28T17:38:38.990-06:00[US/Mountain]
String[] whatTimeIsIt = wholeThing.split("[[-T:.]]"); //wholeThing is a TimeDateZone object converted to a String
String year = whatTimeIsIt[0];
String month = setMonth(whatTimeIsIt[1]);
String day = whatTimeIsIt[2];
String hour = setHour(whatTimeIsIt[3]);
String minute = whatTimeIsIt[4];
String second = setAmPm(whatTimeIsIt[5],whatTimeIsIt[3]);
String timeZone = whatTimeIsIt[8];
Using split() is the right idea.
String[] timeZoneTemp = wholeThing.split("\\[");
String timeZone = timeZoneTemp[1].substring(0, timeZoneTemp[1].length() - 1);
If you want to parse the string yourself, use a regular expression to extract the values.
Don't use a regex to find characters to split on, which is what split() does.
Instead, use a regex with capture groups, compile it using Pattern.compile(), obtain a Matcher on your input text using matcher(), and check it using matches().
If it matches you can get the captured groups using group().
Example regex:
(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d+)[-+]\d{2}:\d{2}\[([^\]]+)\]
In a Java string, you have to escape the \, so here is code showing how it works:
String input = "2016-09-28T17:38:38.990-06:00[US/Mountain]";
String regex = "(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).(\\d+)[-+]\\d{2}:\\d{2}\\[([^\\]]+)\\]";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.matches()) {
System.out.println("Year : " + m.group(1));
System.out.println("Month : " + m.group(2));
System.out.println("Day : " + m.group(3));
System.out.println("Hour : " + m.group(4));
System.out.println("Minute : " + m.group(5));
System.out.println("Second : " + m.group(6));
System.out.println("Fraction: " + m.group(7));
System.out.println("TimeZone: " + m.group(8));
} else {
System.out.println("** BAD INPUT **");
}
Output
Year : 2016
Month : 09
Day : 28
Hour : 17
Minute : 38
Second : 38
Fraction: 990
TimeZone: US/Mountain
UPDATED
You can of course get all the same values using ZonedDateTime.parse(), which will also ensure that the date is valid, something none of the other solutions will do.
String input = "2016-09-28T17:38:38.990-06:00[US/Mountain]";
ZonedDateTime zdt = ZonedDateTime.parse(input);
System.out.println("Year : " + zdt.getYear());
System.out.println("Month : " + zdt.getMonthValue());
System.out.println("Day : " + zdt.getDayOfMonth());
System.out.println("Hour : " + zdt.getHour());
System.out.println("Minute : " + zdt.getMinute());
System.out.println("Second : " + zdt.getSecond());
System.out.println("Milli : " + zdt.getNano() / 1000000);
System.out.println("TimeZone: " + zdt.getZone());
Output
Year : 2016
Month : 9
Day : 28
Hour : 17
Minute : 38
Second : 38
Milli : 990
TimeZone: US/Mountain
I came across this unusual error today. Can anyone explain me what I am doing wrong. Below is the code:
AreStringsPermuted checkStringPerObj = new AreStringsPermuted();
String[] inputStrings = {"siddu$isdud", "siddu$siddarth", "siddu$sidde"};
for(String inputString : inputStrings){
String[] stringArray = inputString.split("$");
if(checkStringPerObj.areStringsPermuted(stringArray[0],stringArray[1]))
System.out.println("Strings : " + stringArray[0] + " ," + stringArray[1] + " are permuted");
else
System.out.println("Strings : " + stringArray[0] + " ," + stringArray[1] + " are not permuted");
}
The above code errors out at when i try to split the string. For some reason split does not work when I try to divide each string using "$". Can any one explain me what I am doing wrong here?
Below is the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at arraysAndStrings.TestClass.checkStringsPermuted(TestClass.java:24)
at arraysAndStrings.TestClass.main(TestClass.java:43)
String.split() takes a regular expression, so you need to quote strings that contain characters that have special meanings in regular expressions.
String regularExpression = Pattern.quote("$");
for (String inputString : inputStrings) {
String[] stringArray = inputString.split(regularExpression);
String.split( ) uses regex partern and $ has special meaning in regex(the end of line).
In your case, use "\$" instead of "$".
String []arrayString = inputString.split("\\$");
For more information,
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
I'm writing some code that is being used to parse dates out of a very large data set. I have the following regex to match different variations of dates
"(((0?[1-9]|1[012])(/|-)(0?[1-9]|[12][0-9]|3[01])(/|-))|"
+"((january|february|march|april|may|june|july|august|september|october|november|december)"
+ "\\s*(0?[1-9]|[12][0-9]|3[01])(th|rd|nd|st)?,*\\s*))((19|20)\\d\\d)"
which matches dates of format 'Month dd, yyyy', 'mm/dd/yyyy', and 'mm-dd-yyyy'. This works fine for those formats, but I'm now encountering dates in the European 'dd Month, yyyy' format. I tried adding (\\d{1,2})? at the beginning of the regex and adding a ? quantifier after the current day matching section of the regex as such
"((\\d{1,2})?((0?[1-9]|1[012])(/|-)(0?[1-9]|[12][0-9]|3[01])(/|-))|"
+"((january|february|march|april|may|june|july|august|september|october|november|december)"
+ "\\s*(0?[1-9]|[12][0-9]|3[01])?(th|rd|nd|st)?,*\\s*))((19|20)\\d\\d)"
but this is not entirely viable as it sometimes captures numeric characters both before and after the month (ex. '00 January 15, 2013') and sometimes neither ('January 2013'). Is there a way to ensure that exactly one of the two is captured?
Give you one Java implementation for your requirements (searching the date from inpiut texts):
String input = "which matches dates of format 'january 31, 1976', '9/18/2013', "
+ "and '11-20-1988'. This works fine for those formats, but I'm now encountering dates" +
"in the European '26th May, 2020' format. I tried adding (\\d{1,2})? at the"+
"beginning of the regex and adding a ? quantifier after the current day matching section of the regex as such";
String months_t = "(january|february|march|april|may|june|july|august|september|october|november|december)";
String months_d = "(1[012]|0?[1-9])";
String days_d = "(3[01]|[12][0-9]|0?[1-9])"; //"\\d{1,2}";
String year_d = "((19|20)\\d\\d)";
String days_d_a = "(" + days_d + "(th|rd|nd|st)?)";
// 'mm/dd/yyyy', and 'mm-dd-yyyy'
String regexp1 = "(" + months_d + "[/-]" + days_d + "[/-]"
+ year_d + ")";
// 'Month dd, yyyy', and 'dd Month, yyyy'
String regexp2 = "(((" + months_t + "\\s*" + days_d_a + ")|("
+ days_d_a + "\\s*" + months_t + "))[,\\s]+" + year_d + ")";
String regexp = "(?i)" + regexp1 + "|" + regexp2;
Pattern pMod = Pattern.compile(regexp);
Matcher mMod = pMod.matcher(input);
while (mMod.find()) {
System.out.println(mMod.group(0));
}
The Output is :
january 31, 1976
9/18/2013
11-20-1988
26th May, 2020
I am using this code to separate the next line and giving space.
String sms="Name:"+name+ System.getProperty ("line.separator")+System.getProperty
("line.separator")+"ContactNumber:"+contactnumber+ System.getProperty
("line.separator")+"Quantity:"+quantity+System.getProperty
("line.separator")+"Number.of.Pcs:"+noofpieces+System.getProperty
("line.separator")+"Date and Time:"+dateandtime
+System.getProperty ("line.separator")+"Delivary
Address:"+deliveryaddress;
You could use a StringBuilder instance and then use the new line operator appended to the StringBuilder. For example:
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(name);
sb.append("\n"); // for a new line.
Whatever the case, I would strongly recommend that you use a StringBuilder to append to a very large String.
In addition, you could also use System.lineSeparator(); However, that may only work in Java with the JVM with Java 7 and not in Android (so I would definitely check that out.)
String sms= "Name:" + name
+ "\nContactNumber:" + contactnumber
+ "\nQuantity:" + quantity
+ "\nNumber.of.Pcs:" + noofpieces
+ "\nDate and Time:" + dateandtime
+ "\nDelivary Address:" + deliveryaddress;
Using System.getProperty("line.separator") is a good practice as it will give you code that could be reused on another platform. To simplify your code, you can use TextUtils.join :
String sms = TextUtils.join(System.getProperty("line.separator"),
new String[] {
"Name:" + name ,
"ContactNumber:" + contactnumber,
...});
You could also use this solution
String format = "Name: %s%n%nContactNumber: %s%nQuantity: %s%nNumber.of.Pcs: %s%nDate and Time: %s%nDelivery Address: %s";
String sms = String.format(format, name, contactnumber, quantity, noofpieces, dateandtime, deliveryaddress);
The explanation of the format placeholders you find in the Javadoc for java.util.Formater