Reputation: 641
I have a String like $29@@rent1@@rent2@@rent3$
. Now, all I want to retrieve is 29
and rent1
then how can I achieve this. Can I use regular expression here?
Any response will be thankful.
Upvotes: 0
Views: 86
Reputation: 36304
Just try using regex with capturing and non- capturing groups. Although splitting it would make more sense(obviously..)
public static void main(String[] args) {
String s = "$29@@rent1@@rent2@@rent3$";
Pattern p = Pattern.compile("\\$(\\d+)(?:@@)(\\w+|\\d+).*"); // capture only 29 and rent1, ignore @@
Matcher m = p.matcher(s);
m.find();
System.out.println(m.group(1));
System.out.println(m.group(2));
}
O/P :
29
rent1
Upvotes: 0
Reputation: 1140
Assume that your string always has the format of ${some strings}$ and those some strings are elements connected by that "@@", and you want to get the first and the second elements.
If that, the first step is to remove the first and last character of the source string:
String new_string = old_string.substring(1, old_string.length() - 1);
Next, split the remaining into an array of sub strings:
String[] elements = new_string.split("@@");
Now get what you want by that arrays. Don't forget to check the length of the result array.
Here is a snippet:
String old_string = "$29@@rent1@@rent2@@rent3$";
// if you don't know how your string looks like, use a try - catch to
// ensure your app will not crush
try {
String new_string = old_string
.substring(1, old_string.length() - 1);
String[] elements = new_string.split("@@");
for (String text : elements) {
System.out.println(text);
}
} catch (Exception er) {
er.printStackTrace();
}
Hope that help.
p.s: in case you want to use StringTokenizer for this question, I suggest you to read this answer first.
Scanner vs. StringTokenizer vs. String.Split
Upvotes: 0
Reputation: 239
You can use the StringTokenizer device.
(Edited)
String STR = "$29@@rent1@@rent2@@rent3$";
StringTokenizer st = new StringTokenizer(STR, "$@");
while(st.hasMoreElements())
Log.v("", "Tokens: " + st.nextToken());
Output:
06-12 11:31:58.228: V/(1045): Tokens: 29
06-12 11:31:58.228: V/(1045): Tokens: rent1
06-12 11:31:58.228: V/(1045): Tokens: rent2
06-12 11:31:58.228: V/(1045): Tokens: rent3
Upvotes: 2