String replace method is not working in android studio - java

I'm not too sure why my word doesn't get replaced in android studio.
private Calendar dateTime = Calendar.getInstance();
private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy, EEE");
String dateFormat = dateFormatter.format(dateTime.getTime());
Button beginDate = (Button) findViewById(R.id.startDate);
beginDate.setText("From " + dateFormat);
// Other codes removed for simplicity
String beginD = beginDate.getText().toString().replace("From: ", "");
Log.d("Test", beginD);
Log result as follows:
06-16 14:14:01.957 23893-23893/packagename D/Testīš• From
16/06/2015, Tue

You're trying to replace "From: " but you only added "From " (without the :).

I don't see : in the input you entered, so From: won't be matched. I recommend using more generic pattern:
replaceAll("From:?\\s+", "");
Since replaceAll takes a regex, you can ask for optional :, followed by one or more space(s).

In your button text is no :. So you have to change the text of the botton to :
beginDate.setText("From: " + dateFormat);
or your regex to
String beginD = beginDate.getText().toString().replace("From ", "");

Related

Java regex to match dates

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

Is there any simpler code to separate lines?

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

Using space as delimiter

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*", "-");

NumberFormatException: unable to parse '' as integer

I have a date string:
gridcell.setTag(theday + "-" + themonth + "-" + theyear + "|" + hijri_day + "-" + hijri_month + " ("+ hijri_monthno +") " + hijri_year);
..which I pass on to another class on button click if the date has an event:
String date_month_year = (String) view.getTag();
if (isHoliday(d, m, y))
{
Intent i = new Intent(view.getContext(), Events.class);
i.putExtra("date_string", date_month_year);
startActivity(i);
}
In the Events.class, I get the parameters:
Intent intent = getIntent();
String date_string = intent.getStringExtra("date_string");
date_view = (TextView) this.findViewById(R.id.hijridate);
eventdetails = (TextView) this.findViewById(R.id.eventdetails);
date_view.setText(date_string);
String[] dateAr = date_string.split("-|\\||\\(|\\)|\\s+");
m = Integer.parseInt(dateAr[6]);
d = Integer.parseInt(dateAr[3]);
y = Integer.parseInt(dateAr[8]);
This is the Hijri month array:
private String months[] = {"Muharram","Safar","Rabi-al Awwal","Rabi-al Thani","Jumada al-Ula","Jumada al-Thani","Rajab","Sha\'ban","Ramadhan","Shawwal","Dhul Qa\'dah","Dhul Hijjah"};
The problem I'm having is that when it's a one word month name (i.e. Muharram, Safar, Rajab, etc. .) everything works smoothly. However, if it's a word with a space or a dash (i.e. Rabi-al awwal, Dhul Hijjah), it throws the error: NumberFormatException: unable to parse '' as integer or NumberFormatException: unable to parse 'al' as integer
What am I doing wrong?
Is there a reason you need to use a lot of different character types to split the string on?
The reason it's failing is because the split characters your using at
String[] dateAr = data_string.split("-|\||\(|\)|\s+");
are also in the month name.
put a debug point after that line, or do a for each over the dateAr array and log the results. That way, you can understand how it's being split.

remove : in 12:45 (java)

time 12:45
i want to remove : in java .. i just need 1245 ..How can i do that?
String time = "12:45".replace( ":", "" ); // "1245"
If you have Apache Coomons Lang in your classpath, and you are not sure that time is not null, you could use StringUtils:
time = StringUtils.remove( time, ":" );
this way is more compact than writing
if ( time != null ) {
time = time.replace( ":", "" );
}
There is the "replace" method.
s = s.replace(':','');
If you want to get fancy:
s = s.replaceAll("[^a-zA-Z0-9]", "");
This will remove all non-alpha numeric characters (including your ':')
All right there in the JavaDoc.
If "12:45" is a string, then just use "12:45".replaceAll(":", "").
String strTime = "12:45";
strTime.replace(':','');
For the easiest method, use replace:
String time = "12:45";
time = time.replace(':', "");
but you can use regular expressions:
Pattern pattern = new Pattern("(\\d{1,2}):(\\d{1,2})");
Matcher matcher = pattern.matcher("12:45");
String noColon = matcher.group(1) + matcher.group(2);
or the String API:
String time = "12:45";
int colonIndex = time.indexOf(':"';
String noColon = time.substring(0, colonIndex) +
time.substring(colonIndex + 1, time.length);
Like what others told, a method as simple as String's replace should suffice, but since i suspect your input is a date, have a look at SimpleDateFormat too.

Categories