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?
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.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: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