I have my String, "08000001066". This String, which is a telephone number should be displayed with correct format as, "0800 000 1066".
One person suggested i should use this code block,
DecimalFormatSymbols phoneNumberSymbols = new DecimalFormatSymbols();
phoneNumberSymbols.setGroupingSeparator(' ');
DecimalFormat phoneNumberFormat = new DecimalFormat("####,###,###", phoneNumberSymbols);
This results in something close to what i want, but not exact as the DecimalFormat required a number (double, or float - of which a zero leading string cannot be parsed).
How would i format a String by method of something like Decimal Format's ####,###,###?
String phoneNumber = "08000001066";
StringBuilder sb = new StringBuilder(phoneNumber)
.insert(4," ")
.insert(8," ");
String output = sb.toString();
Try this out, it relies on your input being the correct number of digits but works with leading zeroes.
String inputString = "08000001066";
java.text.MessageFormat phoneFormat = new java.text.MessageFormat("{0} {1} {2}");
String[] phoneNumberArray = {inputString.substring(0,4), inputString.substring(4,7), inputString.substring(7)};
System.out.println(phoneFormat.format(phoneNumberArray));
Pattern p = Pattern.compile("(\\d{4})(\\d{3})(\\d{4})");
String s = "08000001066";
Matcher m = p.matcher(s);
if(m.matches()) {
return String.format("%s %s %s", m.group(1), m.group(2), m.group(3)));
}
Related
I have searched everywhere for this but couldn't get a specific solution, and the documentation also didn't cover this. So I want to extract the start date and end date from this string "1-Mar-2019 to 31-Mar-2019". The problem is I'm not able to extract both the date strings.
I found the closest solution here but couldn't post a comment asking how to extract values individually due to low reputation: https://stackoverflow.com/a/8116229/10735227
I'm using a regex pattern to look for the occurrences and to extract both occurrences to 2 strings first.
Here's what I tried:
Pattern p = Pattern.compile("(\\d{1,2}-[a-zA-Z]{3}-\\d{4})");
Matcher m = p.matcher(str);
while(m.find())
{
startdt = m.group(1);
enddt = m.group(1); //I think this is wrong, don't know how to fix it
}
System.out.println("startdt: "+startdt+" enddt: "+enddt);
Output is:
startdt: 31-Mar-2019 enddt: 31-Mar-2019
Additionally I need to use DateFormatter to convert the string to date (adding the trailing 0 before single digit date if required).
You can catch both dates simply calling the find method twice, if you only have one, this would only capture the first one :
String str = "1-Mar-2019 to 31-Mar-2019";
String startdt = null, enddt = null;
Pattern p = Pattern.compile("(\\d{1,2}-[a-zA-Z]{3}-\\d{4})");
Matcher m = p.matcher(str);
if(m.find()) {
startdt = m.group(1);
if(m.find()) {
enddt = m.group(1);
}
}
System.out.println("startdt: "+startdt+" enddt: "+enddt);
Note that this could be used with a while(m.find()) and a List<String to be able to extract every date your could find.
If your text may be messy, and you really need to use a regex to extract the date range, you may use
String str = "Text here 1-Mar-2019 to 31-Mar-2019 and tex there";
String startdt = "";
String enddt = "";
String date_rx = "\\d{1,2}-[a-zA-Z]{3}-\\d{4}";
Pattern p = Pattern.compile("(" + date_rx + ")\\s*to\\s*(" + date_rx + ")");
Matcher m = p.matcher(str);
if(m.find())
{
startdt = m.group(1);
enddt = m.group(2);
}
System.out.println("startdt: "+startdt+" enddt: "+enddt);
// => startdt: 1-Mar-2019 enddt: 31-Mar-2019
See the Java demo
Also, consider this enhancement: match the date as whole word to avoid partial matches in longer strings:
Pattern.compile("\\b(" + date_rx + ")\\s*to\\s*(" + date_rx + ")\\b")
If the range can be expressed with - or to you may replace to with (?:to|-), or even (?:to|\\p{Pd}) where \p{Pd} matches any hyphen/dash.
You can simply use String::split
String range = "1-Mar-2019 to 31-Mar-2019";
String dts [] = range.split(" ");
System.out.println(dts[0]);
System.out.println(dts[2]);
I have an android application and today I have got a crash report which contains this:
This exception trigger when the application tries to parse string number which is provided by the user.
It is obvious that problem is the application cannot parse Hindi numbers! So, how can I solve this?
Regex
Using regex would be better if you want to match any unicode digits.The regex would be \\p{N}+ and here's how to use it:
Matcher m=Pattern.compile("\\p{N}+").matcher(input);
if(m.find())
{
System.out.println(m.group());
}
Locale
To answer your question you should use NumberFormat as mentioned in docs. Specify a Locale for NumberFormat.
NumberFormat nf = NumberFormat.getInstance(new Locale("hi", "IN"));
nf.parse(input);
You can use Character.getNumericValue(char).
The good thing about this method is that it can do what you need.
But to work in valid you should implement in your application support for local.
NumberFormat format = NumberFormat.getInstance(new Locale("hin","IND"));
Number parse = format.parse("१");
System.out.println(parse);
Prints 1.
Try this. This will remove non numeric characters.
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str); // str is input String
while(m.find()) {
System.out.println(m.group(1));
}
If you are dealing with double(with decimal places). you can try this
String text = "123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
double numVal = Double.valueOf(numOnly);
System.out.println(numVal);
Use
BigDecimal bigDecimal = new BigDecimal(YOUR_VALUE);
before applying the regex, as the BigDecimal supports 12 integers, 12.35 decimal, and 12 $ currency, 12% percentage and its localized value.
You can use the following method which receives a string and converts every Indian digit inside it to Arabic.
public static String convertAllIndianToArabic(String str)
{
for(int i=0; i<str.length(); i++)
{
if(str.charAt(i)=='٠')
str = str.substring(0, i)+"0"+str.substring(i+1);
else if(str.charAt(i)=='١')
str = str.substring(0, i)+"1"+str.substring(i+1);
else if(str.charAt(i)=='٢')
str = str.substring(0, i)+"2"+str.substring(i+1);
else if(str.charAt(i)=='٣')
str = str.substring(0, i)+"3"+str.substring(i+1);
else if(str.charAt(i)=='٤')
str = str.substring(0, i)+"4"+str.substring(i+1);
else if(str.charAt(i)=='٥')
str = str.substring(0, i)+"5"+str.substring(i+1);
else if(str.charAt(i)=='٦')
str = str.substring(0, i)+"6"+str.substring(i+1);
else if(str.charAt(i)=='٧')
str = str.substring(0, i)+"7"+str.substring(i+1);
else if(str.charAt(i)=='٨')
str = str.substring(0, i)+"8"+str.substring(i+1);
else if(str.charAt(i)=='٩')
str = str.substring(0, i)+"9"+str.substring(i+1);
}
return str;
}
I do have Bulgarian currency in a format like +000000027511,00.I want to convert this format to 27511.00,I have tried it and got using substring combinations and regex,Is there any patterns or regex to do it in more simplified way?
Implementation I tried,
String currency= "+000000027511"; // "[1234]" String
String currencyFormatted=currency.substring(1);
System.out.println(currencyFormatted.replaceFirst("^0+(?!$)", ""));
Using Double.valueOf + DecimalFormat.format, or DecimalFormat.parse + format, or BigDecimal you can do it as this.
// method 1 (parsing to Float)
String s = "+000000027511,00".replace(",", ".");
Double f = Double.valueOf(s);
DecimalFormat df = new DecimalFormat("#########0.00");
String formatted = df.format(f);
System.out.println(formatted);
// method 2 (parsing using Decimal Format)
s = "+000000027511,00";
DecimalFormat df2 = new DecimalFormat("+#########0.00;-#########0.00");
Number n = df2.parse(s);
df = new DecimalFormat("#########0.00");
formatted = df.format(n);
System.out.println(formatted);
// method 3 (using BigDecimal)
BigDecimal b = new BigDecimal(s.replace(",", "."));
b.setScale(2, RoundingMode.HALF_UP);
System.out.println(b.toPlainString());
Will print
27511.00
27511.00
27511.00
Something like this:
String s = "+000000027511,00";
String r = s.replaceFirst("^\\+?0*", "");
r = r.replace(',', '.');
Try
String s = "+000000027511,00";
s = s.replace("+", "").replaceAll("^0+", "").replace(',', '.');
System.out.println(s);
So for example, I have this string:
0no1no2yes3yes4yes
The first 0 here should be removed and used an an index of array. I am doing so by this statement:
string = string.replaceFirst(dataLine.substring(0, 1), "");
However, when I have say this string:
10yes11no12yes13yes14no
My code fails, since I want to process the 10 but my code extracts just the 1.
So in sort, single digits work fine, but double or triple digits cause IndexOutOfBound Error.
Here's the code: http://pastebin.com/uspYp1FK
And here's some sample data: http://pastebin.com/kTQx5WrJ
Here's the output for the sample data:
Enter filename: test.txt
Data before cleanUp: {"assignmentID":"2CCYEPLSP75KTVG8PTFALQES19DXRA","workerID":"AGMJL8K9OMU64","start":1359575990087,"end":"","elapsedTime":"","itemIndex":0,"responses":[{"jokeIndex":0,"response":"no"},{"jokeIndex":1,"response":"no"},{"jokeIndex":2,"response":"yes"},{"jokeIndex":3,"response":"yes"},{"jokeIndex":4,"response":"yes"}],"mturk":"yes"},
Data after cleanUp: 0no1no2yes3yes4yes
Data before cleanUp: {"assignmentID":"2118D8J3VE7W013Z4273QCKAGJOYID","workerID":"A2P0GYVEKGM8HF","start":1359576154789,"end":"","elapsedTime":"","itemIndex":3,"responses":[{"jokeIndex":15,"response":"no"},{"jokeIndex":16,"response":"no"},{"jokeIndex":17,"response":"no"},{"jokeIndex":18,"response":"no"},{"jokeIndex":19,"response":"no"}],"mturk":"yes"},
Data after cleanUp: 15no16no17no18no19no
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1907)
at jokes.main(jokes.java:34)
Basically, what the code is supposed to do is strip off the data into strings as shown above, and then read the number, and if it's followed by yes increase it's index's value in dataYes, or if followed by no increase value in dataNo. Makes sense?
What can I do? How can I make my code more flexible?
An alternative, more specific attempt: -
String regex = "^(\\d+)(yes|no)";
String myStr = "10yes11no";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(myStr);
while (m.find())
{
String all = m.group();
String digits = m.group(1);
String bool = m.group(2);
// do not try and combine the next 2 lines ... it doesn't work!
myStr = myStr.substring(all.length());
m.reset(myStr);
System.out.println(String.format("all = %s, digits = %s, bool = %s", all, digits, bool));
}
does it work for you?
string = string.replaceAll("^\\d+","");
Try this
System.out.println("10yes11no12yes13yes14no".replaceFirst("^\\d+",""));
How about: -
String regex = "^\\d+";
String myStr = "10abc11def";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(myStr);
if(m.find())
{
String digits = m.group();
myStr = m.replaceFirst("");
}
I have a string which contains many <xxx> values.
I want to retrive the value inside <>, do some manipulation and re-insert the new value into the string.
What I did is
input = This is <abc_d> a sample <ea1_j> input <lmk_02> string
while(input.matches(".*<.+[\S][^<]>.*"))
{
value = input.substring(input.indexOf("<") + 1, input.indexOf(">"));
//calculate manipulatedValue from value
input = input.replaceFirst("<.+>", manipulatedValue);
}
but after the first iteration, value contains abc_d> a sample <ea1_j> input <lmk_02. I believe indexOf(">") will give the first index of ">". Where did I go wrong?
This is a slightly easier way of accomplishing what you are trying to do:
String input = "This is <abc_d> a sample <ea1_j> input <lmk_02> string";
Matcher matcher = Pattern.compile("<([^>]*)>").matcher(input);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, manipulateValue(matcher.group(1)));
}
matcher.appendTail(sb);
System.out.println(sb.toString());
This is a good use case for the appendReplacement and appendTail idiom:
Pattern p = Pattern.compile("<([^>]+)>");
Matcher m = p.matcher(input);
StringBuffer out = new StringBuffer():
while(m.find()) {
String value = m.group(1);
// calculate manipulatedValue
m.appendReplacement(out, Matcher.quoteReplacement(manipulatedValue));
}
m.appendTail(out);
Try using an escape character \\ to the regex.