How to get all substrings from captured groups in regex in Vala?

106 Views Asked by At

I am writing an aplication in Vala that uses regex. What I need to do is wrap all hashtags in string in tags. And I don't quite understand how regex works in Vala.

Currently I am trying to do something like this:

Regex hashtagRegex = new Regex("(#[\\p{L}0-9_]+)[ #]");
MatchInfo info;

if (hashtagRegex.match_all_full(string, -1, 0, 0, out info))
{
    foreach(string hashTag in info.fetch_all())
        string = string.replace(hashTag, "<a href=\"" + hashTag + "\">" + hashTag + "</a>");
}

but it parses only first hashtag and with the space on the end of it.

I am using [ #] at the end of the regex because some users don't separate hashtags with spaces and just write bunch of hashtags like this: #hashtag1#hashtag2#hashtag3 and I want to handle it too.

What I need to do is to somehow get an array of all hashtags in string to use it to wrap all of them in tags. How can I do it?

1

There are 1 best solutions below

0
On BEST ANSWER

What I need to do is to somehow get an array of all hashtags in string to use it to wrap all of them in tags. How can I do it?

No it isn't.

Try something like this:

private static int main (string[] args) {
    try {
        GLib.Regex hashtagRegex = new GLib.Regex ("#([a-zA-Z0-9_\\-]+)");
        string res = hashtagRegex.replace_eval ("foo #bar baz #qux qoo", -1, 0, 0, (mi, s) => {
                s.append_printf ("<a href=\"%s\">%s</a>", mi.fetch (1), mi.fetch (0));
                return false;
            });
        GLib.message (res);
    } catch (GLib.Error e) {
        GLib.error (e.message);
    }

    return 0;
}

I don't know what characters are valid in a hash tag, but you can always tweak the regex as needed. The important part is using a callback to perform the replacement.