Multiply Integers Inside A String By An Individual Value Using Regex - android

I currently have the code below and it successfully returns all the numbers that are present in a string I have.
An example of the string would be say: 1 egg, 2 rashers of bacon, 3 potatoes.
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
while (matcher.find()) {
Toast.makeText(this, "" + matcher.group(), Toast.LENGTH_LONG).show();
}
However, I would like to multiply these numbers by say four and then place them back in the original string. How can I achieve this?
Thanks in advance!

I've never tried this, but I think appendReplacement should solve your problem

Doing arithmetic is a little complicated while doing the find()
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(test);
int start = 0;
int end = 0;
StringBuffer resultString = new StringBuffer();
while (matcher.find()) {
start = matcher.start();
// Copy the string from the previous end to the start of this match
resultString.append(test.substring(end, start));
// Append the desired new value
resultString.append(4 * Integer.parseInt(matcher.group()));
end = matcher.end();
}
// Copy the string from the last match to the end of the string
resultString.append(test.substring(end));
This StringBuffer will hold the result you are expecting.

Related

How to truncate decimal value in a text

So, I need to show a string in UI which has both numbers and text together.
Something like this,
10.289 Mbps
and I wanted to remove .289 and just show 10 Mbps
I tried a lot of options like setting text as
String rounded = String.format("%.0f", speedValue);
But nothing seems to be working for me.
Appreciate any help.
This can be possible in many ways.
Split String
String inputStr = "10.289 Mbps";
String[] splited = inputStr.split(" ");
Double val = Double.parseDouble(splited[0]);
System.out.println("Value : "+val.intValue()+" "+splited[1]);
Regx
Pattern pattern = Pattern.compile("(([0-9]+)(.)?([0-9]+)?) ([A-Z,a-z]+)", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.find())
{
System.out.println("Value : "+matcher.group(2)+" "+matcher.group(5));
}
something like this can work:
string = "10.289 Mbps"
string_list = string.split(" ")
number = string_list[0]
number = float(number)
print(round(number))
basically isolate the number bu removing 'Mbps' then cast it to a float value and round it to get an integer.
try this
String str = "10.289 Mbps";
String[] strArray = str.split(" ");
Long roundedValue = Math.round(Double.valueOf(strArray[0]));
String resultStr = roundedValue.toString() + " " + strArray[1];
System.out.println(resultStr);

Split datetime from string android

I have String s = http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/
(Using Java android)how to split date string 23-4-2015 from it become two substring:
http://kqxs.net.vn/xo-so-ngay/an-giang-xsag
23-4-2015
Use the substring method
String str = "http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/";
url = str.substring(0, 43);
date = str.substring(44, 53);
I hope the date will always be on the last. So you can actualy do Java substring take the last 11 char from the end. Because there is "/".
Hard way you can actually do a RegEx to get only a number. But it is not possible if in the URL there is a numerical too.
Try this using regular expressions,
String str = "http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/";
String regexStr = "\\d{2}-\\d{1,2}-\\d{4}";
Pattern pattern = Pattern.compile(regexStr);
Matcher matcher = pattern.matcher(str);
int startIndex=-1;
// Check all occurrences
while (matcher.find()) {
startIndex = matcher.start();
}
if(startIndex>0){
String firstPart = str.substring(0,startIndex-1);
String secondPart = str.substring(startIndex);
System.out.println("First Part "+firstPart);
System.out.println("Second Part "+secondPart);
}else{
System.out.println("Match Not Found!");
}
Output:-
First Part http://kqxs.net.vn/xo-so-ngay/an-giang-xsag
Second Part 23-4-2015/
Try This code for The Get the date from the String.
String str="fgdfg12°59'50\" Nfr | gdfg: 80°15'25\" Efgd";
String[] spitStr= str.split("\\|");
String numberOne= spitStr[0].replaceAll("[^0-9]", "");
String numberSecond= spitStr[1].replaceAll("[^0-9]", "");
Try this another code
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}

How to split this String?

I want to split this string
String info = "0.542008835 meters height from ground";
from this i want to get only two decimals like this 0.54.
by using this i am getting that
String[] _new = rhs.split("(?<=\\G....)");
But i am facing problem here, if string does't contain any decimals like this string
String info = "1 meters height from ground";
for this string i am getting those characters upto first 4 in the split string like 1 me.
i want only numbers to split if it has decimals, How to solve this problem.
if(info.contains("."))
{
String[] _new = rhs.split("(?<=\\G....)");
}
I think you can check by white space after first value. see this
If you get the space then get first character only.
For checking if a string contains whitespace use a Matcher and call it's find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
You could use a regex to do this as an alternative to Deepzz's method, this will handle the case where there is a '.' in the later part of the String, I've included an example below. It's not clear from your question is you actually want to remaining part of the String, but you could add a second group to the reg ex to capture this.
public static void main(String[] args) {
final String test1 = "1.23 foo";
final String test2 = "1 foo";
final String test3 = "1.234 foo";
final String test4 = "1.234 fo.o";
final String test5 = "1 fo.o";
getStartingDecimal(test1);
getStartingDecimal(test2);
getStartingDecimal(test3);
getStartingDecimal(test4);
getStartingDecimal(test5);
}
private static void getStartingDecimal(final String s) {
System.out.print(s + " : ");
Pattern pattern = Pattern.compile("^(\\d+\\.\\d\\d)");
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
System.out.println(matcher.group(1));
} else {
System.out.println("Doesn't start with decimal");
}
}
Assuming the number is always the first part of the string:
String numStr = rhs.split(" ")[0];
Double num = Double.parseDouble(numStr);
After that you can use the String Formatter to get the desired representation of the number.
This will work when you know the String near the numbers, with int and double numbers as well.
String a ="0.542008835 meters height from ground";
String b = a.replace(" meters height from ground", "");
int c = (int) ((Double.parseDouble(b))*100);
double d = ((double)c/100);

\n (Newline) deleting Android

There was some XML parsed text that looked like this:
06:00 Vesti<br>07:15 Something Else<br>09:10 Movie<a href="..."> ... <br>15:45 Something..
and there was a lot of it..
Well, I have done this:
String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
there was no other way to show text nicely.
Now, after few showings, and some time, I need that same text separated into alone strings like this:
06:00 Vesti
... or
07:15 Something Else
I've tried something like this, but it does not work:
char[] rast = description.toCharArray();
int brojac = 0;
for(int q=0; q<description.length(); q++){
if(rast[q]=='\\' && rast[q+1]=='n' ) brojac++;
}
String[] niz = new String[brojac];
int bf1=0;
int bf2=0;
int bf3=0;
int oo=0;
for(int q=0; q<description.length(); q++){
if(rast[q]=='\\'&& rast[q+1]=='n'){
bf3=bf1;
bf1=q;
String lol = description.substring(bf3, bf1);
niz[oo]=lol;
oo++;
}
}
I know that in description.substring(bf3,bf1) are not set as they should be but I think that this:
if(rast[q]=='\\' && rast[q+1]=='n)
does not work that way.. is there any other solution?
Note. there is no other way to get that resource. , It must be through this.
Calling Html.fromHtml(String) will properly translate the <br> into \n.
String html = "06:00 Vesti<br>07:15 Something Else<br>09:10 Movie<a href=\"...\"> ... <br>15:45 Something..";
String str = Html.fromHtml(html).toString();
String[] arr = str.split("\n");
Then, just split it on a line basis - no need for regexps (which you shouldn't be using to parse HTML in the first case).
Edit: Turning everything into a bunch of Dates
// Used to find the HH:mm, in case the input is wonky
Pattern p = Pattern.compile("([0-2][0-9]:[0-5][0-9])");
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
SortedMap<Date, String> programs = new TreeMap<Date, String>();
for (String row : arr) {
Matcher m = p.matcher(row);
if (m.find()) {
// We found a time in this row
ParsePosition pp = new ParsePosition(m.start(0));
Date when = fmt.parse(row, pp);
String title = row.substring(pp.getIndex()).trim();
programs.put(when, title);
}
}
// Now programs contain the sorted list of programs. Unfortunately, since
// SimpleDateFormat is stupid, they're all placed back in 1970 :-D.
// This would give you an ordered printout of all programs *AFTER* 08:00
Date filter = fmt.parse("08:00");
SortedMap<Date, String> after0800 = programs.tailMap(filter);
// Since this is a SortedMap, after0800.values() will return the program names in order.
// You can also iterate over each entry like so:
for (Map.Entry<Date,String> program : after0800.entrySet()) {
// You can use the SimpleDateFormat to pretty-print the HH:mm again.
System.out.println("When:" + fmt.format(program.getKey()));
System.out.println("Title:" + program.getValue());
}
Use regex:
List<String> results = new ArrayList<String>();
Pattern pattern = Pattern.compile("(\d+:\d+ \w+)<?");
Matcher matcher = pattern.matcher("06:00 Vesti<br>07:15 Something Else<br>09:10 Movie<a href="..."> ... <br>15:45 Something..");
while(matcher.find()) {
results.add(matcher.group(0));
}
results will end up as a list of strings:
results = List[
"06:00 Vesti",
"07:15 Something Else",
"09:10 Movie",
"15:45 Something.."]
See Rexgex Java Tutorial for an idea of how javas regex library works.

Extract substring from a string

what is the best way to extract a substring from a string in android?
If you know the Start and End index, you can use
String substr=mysourcestring.substring(startIndex,endIndex);
If you want to get substring from specific index till end you can use :
String substr=mysourcestring.substring(startIndex);
If you want to get substring from specific character till end you can use :
String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue"));
If you want to get substring from after a specific character, add that number to .indexOf(char):
String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue") + 1);
substring():
str.substring(startIndex, endIndex);
Here is a real world example:
String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1);
In the example asubstring would return: h
There is another way , if you want to get sub string before and after a character
String s ="123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];
check this post-
how to find before and after sub-string in a string
substring(int startIndex, int endIndex)
If you don't specify endIndex, the method will return all the
characters from startIndex.
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Example:
String str = "abcdefgh"
str.substring(0, 4) => abcd
str.substring(4, 6) => ef
str.substring(6) => gh
you can use this code
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
Log.d("message", "" + mainString.substring(startIndex, endIndex));
endString = mainString.substring(startIndex, endIndex);
return endString;
}
in this mainString is a Super string.like
"I_AmANDROID.Devloper"
and lastString is a string like"." and startString is like"_".
so this function returns "AmANDROID".
enjoy your code time.:)
use text untold class from android: TextUtils.substring (charsequence source, int start, int end)
You can use subSequence , it's same as substr in C
Str.subSequence(int Start , int End)
When finding multiple occurrences of a substring matching a pattern
String input_string = "foo/adsfasdf/adf/bar/erqwer/";
String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input_string);
while(matcher.find()) {
String str_matched = input_string.substring(matcher.start(), matcher.end());
// Do something with a match found
}
The best way to get substring in Android is using (as #user2503849 said) TextUtlis.substring(CharSequence, int, int) method. I can explain why. If you will take a look at the String.substring(int, int) method from android.jar (newest API 22), you will see:
public String substring(int start) {
if (start == 0) {
return this;
}
if (start >= 0 && start <= count) {
return new String(offset + start, count - start, value);
}
throw indexAndLength(start);
}
Ok, than... How do you think the private constructor String(int, int, char[]) looks like?
String(int offset, int charCount, char[] chars) {
this.value = chars;
this.offset = offset;
this.count = charCount;
}
As we can see it keeps reference to the "old" value char[] array. So, the GC can not free it.
In the newest Java it was fixed:
String(int offset, int charCount, char[] chars) {
this.value = Arrays.copyOfRange(chars, offset, offset + charCount);
this.offset = offset;
this.count = charCount;
}
Arrays.copyOfRange(...) uses native array copying inside.
That's it :)
Best regards!
All of The responders gave good answers. However, I am giving you all relatable methods for this so that any one can get from one place, I'll edit my answer if I find something new.
substring(0)- use for cut string from given specific char.
Substring(0,2)- give you sub string from starting(0) and ending(2) characters.
Split("NAME")- return you string in two parts first is that you use in split "NAME" and another part is rest of string combine.
subSequence(0,3) - returns sequence of give start(0) and ending index(3).
This one is not specifically use for split string but though it may be use full for some one
startswith("A",3)- returns string for specific starting character.
For example:
String s = "StackOverflow";
String[] split = s.split("Stack");
System.out.println("STRING NAME:"+s.substring(2));
System.out.println("STRING NAME:"+s.substring(2,3));
System.out.println("STRING NAME:"+split[1]);
System.out.println("STRING NAME:"+split[0]);
System.out.println("STRING NAME:"+s.subSequence(2,5));
Output:
1)ackOverflow
2)a
3)Overflow
4)stack
5)ack
I hope this will give you enough information that you require.

Categories

Resources