Android get data using regexp - android

I have a html string in in which i am trying to get string between the tag using regexp and finally saving the value to array-list . But i am not able to get the string between the tag so my array-list is always empty.
<span><div style=\'float:left; width:350px;\'>Pharmacie DAR D\'BAGH</div>
my code to get the data using regexp is
private void findTextByRegExp()
{
ArrayList<ArrayList<String>>dataList1 = new ArrayList<ArrayList<String>>();
String pattern3 = "<span><div style=\'float:left; width:350px;\'>";
String pattern4 = "</div>";
String text = readFromFile();
Pattern p = Pattern.compile(Pattern.quote(pattern3) + "(.*?)" +
Pattern.quote(pattern4));
Matcher m = p.matcher(text);
while (m.find()) {
ArrayList<String>dataAdd = new ArrayList<String>();
dataAdd.add(m.group(1));
dataList1.add(dataAdd);
Log.d("Group data", "" + m.group(1));
}
Log.d("MY ARRAY LIST OD DATA", "" + dataList1);
}
please help me how to achieve this using regexp?

try
String pattern3 = "<span><div style=\\'float:left; width:350px;\\'>";

Related

how to get the indexes of all the occurences of words in string?

I want to get indexes of all the occurences of string_to_be_search
Input:
String line="hello this is prajakta , how are you?? hello this is prajakta!"
String text_to_search= "hello this is prajakta"
Here the occurrences of text_to_search is 2 so I need list of starting indexes
Output:
List l=[0,39]
Also I have tried a code below
public List getIndexesOfMultipleOccuredString(String originalString,String textToSearch) {
int i, last = 0, count = 0;
List l = new ArrayList();
do {
i = originalString.indexOf(textToSearch, last);
if (i != -1) l.add(i);
last = i + textToSearch.length();
} while (i != -1);
return l;
}
BUT
if my input is as follows
String line="hello this is prajakta ,i love to drive car and i am a carpainter"
String text_to_search="car"
Output:
It gives me two indexes as carpainter contains car which i don't want
Output should be [39]
This is how you do it using regex(word matching)
String line= "hello this is prajakta , how are you?? hello this is prajakta!";
String text_to_search = "\\bhello this is prajakta\\b";
ArrayList<Integer> list = new ArrayList<>();
Pattern p = Pattern.compile(text_to_search);
Matcher m = p.matcher(line);
while (m.find()) {
list.add(m.start());
}
Log.i("All occurrences", "values are " + list.toString());
Output: [0, 39]
If you search using these strings
String line="hello this is prajakta ,i love to drive car and i am a carpainter";
String text_to_search="car";// use as "\\bcar\\b"
Output [40]

How to get the searched text in a string?

I want to get a text that it is a part of an string.For example: I have a string like "I am Vahid" and I want to get everything that it's after "am".
The result will be "Vahid"
How can I do it?
Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid
Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid
Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
result = text.substring(index + after.length());
}
System.out.print(result);
Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
if(stringyouwanttoTrim.contains("I am")
{
return stringyouwanttoTrim.split("I am")[1].trim();
}
else
{
return stringyouwanttoTrim;
}
}
If you prefer to split your sentence by blank space you could do like this :
String [] myStringElements = "I am Vahid".split(" ");
System.out.println("your name is " + myStringElements[myStringElements.length - 1]);

ReplaceAll not working

I'm using google volley to retrieve source code from website. Some looping was done to capture the value in the code. I've successfully captured the data I wanted, but error was shown: NumberFormatException: Invalid float: "2,459.00"
My intention was to store the value after the class=ListPrice>
Sample:
RM 2,899.00
The example value of the source code I wanted to save is "RM2,459.00 "
Below is the code I've written:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lazada_result);
lelongResult = (TextView) findViewById(R.id.lelong_result);
RequestQueue lelong = MyVolley.getRequestQueue(this);
StringRequest myLel = new StringRequest(
Method.GET,
"http://list.lelong.com.my/Auc/List/List.asp?DA=A&TheKeyword=iphone&x=0&y=0&CategoryID=&PriceLBound=&PriceUBound=",
RetrieveLelong(), createMyReqErrorListener());
lelong.add(myLel);
}
private Response.Listener<String> RetrieveLelong() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Float> integers = new ArrayList<>();
String to = "class=ListPrice>";
String remainingText = response;
String showP = "";
while (remainingText.indexOf(to) >= 0) {
String tokenString = remainingText.substring(remainingText
.indexOf(to) + to.length());
String priceString = tokenString.substring(0,
tokenString.indexOf("<"));
float price = Float.parseFloat(priceString.replaceAll("[^\\d,]+", "").trim());
integers.add((price / 100));
remainingText = tokenString;
}
for (int i = 0; i < integers.size(); i++) {
String test1 = Float.toString(integers.get(i));
showP += test1 + "\n";
}
lelongResult.setText(showP);
}
};
}
The problem was as below:
I've tried all sort of replaceAll(),
1)replaceAll("[^\d,]+","") result:2,89900
replace all character except digits and comma works.
2)replaceAll("[^\d]+","") result:Invalid int""
replace all character include comma and dot ,not working
3)replaceAll("[^\d.]+,"") result:Invalid int""
replace all character exclude digits and dot, not working
From the experiment 2&3 coding above,I've noticed that if the comma were removed,i cant parseFloat as the value received by it is: "".NumberFormatException:Invalid Float:"" shown.
From the experiment 1,NumberFormatException:Invalid Float "2,45900" is showned.
The problem was replacing comma ,the code will not work but with the presence of comma ,the value cannot be stored into string
try this:
float price = Float.parseFloat(priceString.replaceAll("RM", "").trim());
use `replaceAll(Pattern.quote(","), "");
EDIT
if you want only numbers then use this
String s1= s.replaceAll("\D+","");
Try to parse the number by specifying the Locale.
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();
I'm just guessing the locale, don't know what you should use, depends on country
You need to do it one by one
priceString=priceString.replaceAll("\\D", "");
priceString=priceString.replaceAll("\\s", "");
now
priceString=priceString.trim();
float price = Float.parseFloat(priceString);
the problem is that in your code:
priceString.replaceAll(Pattern.quote(","), "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
You are replacing coma but not storing the value!
you have to do:
priceString = priceString.replaceAll(",", "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
I'm not sure of the pattern "\D+\s" because if you remove the coma you don't need to replace anything else (except "RM" that i assume you already removed)
Update: set locale and parse a number:
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();

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 a string using regex

I'm parsing a json file with this code:
JSONObject stationJson = array.optJSONObject(i);
Station s = new Station();
s.setName(stationJson.optString("name"));
s.setTimestamp(stationJson.optString("last_update"));
s.setNumber(stationJson.optInt("number"));
This is the json file :
{
"number": 123,
"contract_name" : "7500 - London",
"name": "nom station",
"address": "adresse indicative",
}
I would like to display just the "London" in the name section not the Number.
I found this Code Snippet but I don't know how to use it :
case spots:
number = pSpotsJSON.optString("id");
name = pSpotsJSON.optString("name");
address = pSpotsJSON.optString("description");
status = pSpotsJSON.optString("status");
displayName = buildDisplayName(name);
break;
default:
throw new IllegalArgumentException("Cannot parse spots from JSON: unknown provider " + provider.getName());
}
}
private String buildDisplayName(String name) {
String regexp = "[\\d\\s]*([a-zA-Z](.*)$)";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(name);
if (m.find()) {
return m.group();
}
return name;
}
Any help would be great!
What about getting a substring after the "-" of your String?
Would give something like this:
String contractName = stationJson.getString("contract_name");
contractName = contractName.substring(contractName.indexOf("-")+2); //+2 for the minus + space caracters

Categories

Resources