Search code examples
androidstring-parsing

Scan string for characters and return bounded text


I am writing a dictionary-type app. I have a list of hash-mapped terms and definitions. The basic premise is that there is a list of words that you tap on to see the definitions.

I have this functionality up and running - I am now trying to put dynamic links between the definitions.

Example: say the user taps on an item in the list, "dog". The definition might pop up, saying "A small furry [animal], commonly kept as a pet. See also [cat].". The intention is that the user can click on the word [animal] or [cat] and go to the appropriate definition. I've already gone to the trouble of making sure that any links in definitions are bounded by square brackets, so it's just a case of scanning the pop-up string for text [surrounded by brackets] and providing a link to that definition.

Note that definitions can contain multiple links, whilst some don't contain any links.

I have access to the string before it is displayed, so I guess the best way to do this is to do the scanning and ready the links before the dialog box is displayed.

The question is, how would I go about scanning for text surrounded by square brackets, and returning the text contained within those brackets?

Ideally the actual dialog box that is displayed would be devoid of the square brackets, and I need to also figure out a way of putting hyperlinks into a dialog box's text, but I'll cross that bridge when I come to it.

I'm new to Java - I've come from MATLAB and am just about staying afloat, but this is a less common task than I've had to deal with so far!


Solution

  • You could probably do this with a regular expression; something like this:

    ([^[]*)(\[[^]]+\])
    

    which describes two "match groups"; the first of which means any string of zero or more characters that aren't "[" and the second of which means any string starting with "[", containing one or more characters that aren't "]", and ending with "]".

    Then you could scan through your input for matches to this pattern. The first match group is passed through unchanged, and the second match group gets converted to a link. When the pattern stops matching your input, take whatever's left over and transmit that unchanged as well.

    You'll have to experiment a little; regular expressions typically take some debugging. If your link text can only contain alphanumerics and spaces, your pattern would look more like this:

    ([^[]*)(\[[\s\w]+\])
    

    Also, you may find that regular expression matching under Android is too slow to be practical, in which case you'll have to use wasyl's suggestion.