How can I get patterns using find() method and store the matched patterns in a arraylist
Input string: 9547235617/7865421341
I want to fetch both numbers and pass it in to an arrary list.
Current I am using the below pattern compile method to find the patterns as follows
Pattern number = Pattern.compile("^[789]\\d{9}$");
Matcher matcher = number.matcher(list_string);
if (!matcher.matches()) {
arraylist.add("No number available");
}
elseif (matcher.find()) {
arraylist.add(matcher.group());
}
Log.e("Arraylist value is","==>"+arraylist.tostring());
In this methods it always go the the first if condition and when a try to run the same string in other regex testing program on online examples it only matches the last number as pattern I don't have any idea what to do next hope some one can help
output: Arraylist value is ==>No number available
Note: I need to fetch both numbers and add it to array list.Currently I have used splits for special characters and store those splits in to array list but i want a method regarding regex pattern matching.
matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex.
Regex: (?<=^|\/)(?:\b[7-9]\d{9}\b)?
Java code:
String[] aStr = {"9547235617/7865421341", "6547235617/5865421341", "4547235617/9865421341"};
for(String str: aStr) {
Matcher matcher = Pattern.compile("(?<=^|\\/)(?:\\b[7-9]\\d{9}\\b)?").matcher(str);
while(matcher.find()){
if(matcher.group().equals("")) {
System.out.print("No number available" + "\n");
} else {
System.out.print(matcher.group() + "\n");
}
}
}
Output:
9547235617
7865421341
No number available
No number available
No number available
9865421341
Code demo
Related
I want to retrieve few characters from string i.e., String data on the basis of first colon (:) used in string . The String data possibilities are,
String data = "smsto:....."
String data = "MECARD:....."
String data = "geo:....."
String data = "tel:....."
String data = "MATMSG:....."
I want to make a generic String lets say,
String type = "characters up to first colon"
So i do not have to create String type for every possibility and i can call intents according to the type
It looks like you want the scheme of a uri. You can use Uri.parse(data).getScheme(). This will return smsto, MECARD, geo, tel etc...
Check out the Developers site: http://developer.android.com/reference/android/net/Uri.html#getScheme()
Note: #Alessandro's method is probably more efficient. I just got that one off the top of my head.
You can use this to get characters up to first ':':
String[] parts = data.split(":");
String beforeColon = parts[0];
// do whatever with beforeColon
But I don't see what your purpose is, which would help giving you a better solution.
You should use the method indexOf - with that you can get the index of a certain char. Then you retrieve the substring starting from that index. For example:
int index = string.indexOf(':');
String substring = string.substring(index + 1);
I am developing an application that uses MultiAutoCompleteTextView for showing hints in the drop down list.In this application I retrieve the value written in the MultiAutoCompleteTextView by using
multitextview.getText();
and then query this value to server to recieve JSON response which is shown as suggestions in the drop down list.
If a user types Mu and then Selects music from the list and then types box for another suggestion the content in the MultiAutoCompleteTextView becomes Music,box and now the value for querying to the server is Music,box instead of this I want to select only box.
My question is how to retrieve text written after "," in MultiAutoCompleteTextView?
Can this be achieved using getText()?
I solved this issue
String intermediate_text=multitextview.getText().toString();
String final_string=intermediate_text.substring(intermediate_text.lastIndexOf(",")+1);
I'm sure there are several ways to get around this. One way to do it would be:
String textToQuerryServer = null;
String str = multitextview.getText().toString(); // i.e "music, box" or "any, thing, you , want";
Pattern p = Pattern.compile(".*,\\s*(.*)");
Matcher m = p.matcher(str);
if (m.find()) {
textToQuerryServer = m.group(1);
System.out.println("Pattern found: "+ textToQuerryServer);
}else {
textToQuerryServer = str;
System.out.println("No pattern: "+ textToQuerryServer);
}
I currently have this code below:
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
matcher.find();
String inputInt = matcher.group();
What currently happens is that using Regex, it finds the first integer inside a string and separates it so that I can carry out actions on it. The string that I am using to find integers inside of has many integers and I want them all separate. How can I tweak this code so that it also records the other integers from the string, not just the first one.
Thanks in advance!
In your posted code:
matcher.find();
String inputInt = matcher.group();
You are matching the whole string with a single call to find. And then assigning the first match of digits to your String inputInt. So for example, if you have the below string data, your return will only be 1.
1 egg, 2 bacon rashers, 3 potatoes
You should use a while loop to loop over your matches.
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
while (matcher.find()) {
System.out.println(matcher.group());
}
I've got a HTML code stored in string and I want to extract all parts that match the pattern, which is:
<a href="http://abc.pl/(.*?)/(.*?)"><img src="(.*?)"
(.*?) stands for any string. I've tried dozens of combinations and couldn't get it working. Can somebody show me a sample code, which extracts all matched data from a String and store it in variables?
Thanks in advance
Here is a solution using JavaScript. I hope this helps.
First, we need a working pattern:
var pattern = '<a href="http://abc.pl/([^/"]+)/([^/"]*)".*?><img src="([^"]*)"';
Now, the problem is that in JavaScript there is no native method or function that retrieves both all matches and all submatches at once, whatever the regexp we use.
We can easily retrieve an array of all the full matches:
var re = new RegExp(pattern, "g");
var matches = yourHtmlString.match(re);
But we also want the submatches, right? In my humble opinion, the simplest way to achieve this is to apply the non-greedy version of the same regexp to each match we obtained (because only non-greedy regexes can return submatches):
var reNonGreedy = new RegExp(pattern);
var matchesAndSubmatches = [];
for(var i = 0; i < matches.length; i++) {
matchesAndSubmatches[i] = matches[i].match(reNonGreedy);
}
Each element of matchesAndSubmatches is now an array such that:
matchesAndSubmatches[n][0] is the n-th full match,
matchesAndSubmatches[n][1] is the first submatch of the n-th full match,
matchesAndSubmatches[n][2] is the second submatch of the n-th full match, and so on.
Well, here's the sample:
Pattern pattern = Pattern.compile("patternGoesHere");
Matcher matcher = pattern.matcher(textGoesHere);
while (matcher.find())
{
// You can access substring here via matcher.group(substringIndex) [note they are indexed from 1, not 0]
}
I am trying to validate my string with the regular expression. Here is what I am trying to do
EditText serialText = (EditText) findViewById(R.id.pinText);
serialText.setVisibility(View.VISIBLE);
serialNumber = serialText.getText().toString();
I am storing the serial number in serialNumber
I have the following method to match the regular expression
boolean isRegularSerialNumber(String pinNumber) {
// regular expression to be matched against
String regularString = "[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}";
Pattern pattern = Pattern.compile(regularString);
Matcher matcher = pattern.matcher(pinNumber);
boolean isRegularSerialNumberValid ;
if (pinNumber.matches(regularString))
isRegularSerialNumberValid = true;
else
isRegularSerialNumberValid = false;
return isRegularSerialNumberValid;
}
But I am not able to match this.
Any answer for this? Hope Pattern and Matcher are the right one for this.
What I am trying to do is this, this matched serialNumber I am validating against serial number stored in the database. If match found, it returns success or else failure. And i have entered the exact serial number which is stored in the database but even then it returns failure.
I followed the method what #Stevehb said and i got the match true in that case.
This is how I am sending my data
parameter.add(new BasicNameValuePair("validate", serialNumber));
Breaking my head on this.
The built in String functions should work by themselves. isRegularSerialNumber() could just be
boolean isRegularSerialNumber(String pinNumber) {
String regularString = "[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}";
return pinNumber.matches(regularString);
}
This works for me when I tested 1234-5678-9012-1324 (true) and 12-1234-123-1324 (false).
Also, it looks like you're maybe grabbing the input string from serialText right after you make it visible. Could your problem be in grabbing the text before the user has made any input?
looks much alike .net regex code.
instead of
if (pinNumber.matches(regularString))
try
if (matcher.matches())