0

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.

sam18
  • 631
  • 10
  • 24

3 Answers3

2

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
Bmuller
  • 229
  • 1
  • 6
0

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

Community
  • 1
  • 1
Nguyễn Hoài Nam
  • 1,090
  • 1
  • 9
  • 19
0

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
TheLostMind
  • 34,842
  • 11
  • 64
  • 97