Making objects in Android from regex

54 Views Asked by At

I am writing an Android application which gets string to parse using regex. Let's say it gets

'Tis an example image of a beaver {[beaver.jpg]} having an afternoon tea.

And what I want to get is TextView with 'Tis an example image of a beaver, ImageView beaver.jpg and an another TextView having an afternoon tea..

How (if possible) is creating objects possible after reading such string and parsing with regex?

1

There are 1 best solutions below

1
On

Your custom view class should have a constructor that takes three String parameters, one for the path of the image, one for text to be displayed before the image and one for the text to display afterwards.

class YourView { 
    public YourView(String imgPath, String beforeImg, String afterImg){ 
         //add TextView for text before image 
         //add ImageView for image 
         //add TextView for text after image 
    }
}

If your image will always be enclosed in a {[ ]}, the regex (.+)\\{\\[(.+)\\]\\}(.+) will capture everything before the {[ in capturing group 0, everything between {[ and }] (i.e. the image path) in group 1, and everything after }] in group 2.

If you use a Java Matcher You can then achieve your desired result like:

    String pre, path, post; 
    while (matcher.find()){ 
        pre = matcher.group(0);
        path = matcher.group(1);
        post = matcher.group(2); 
        YourView view = new YourView(path, pre, post); 
        //add view 
    }

Note that, if the image is at the end or beginning of the text, you'll simply be passing empty strings as the third/first parameters here, which will result in the creation of empty TextViews, which should be harmless (or you can do a check and not create one for empty strings).

That said, also note that above code is untested (but should give you the general idea), and that I'm a Java programmer with little experience in Android - so let me know if there's an Android-specific reason this wouldn't work