How to find out the words start with # in string

787

Solution 1

You can use Regex to find all words starting with the character #. Then use Text.rich or RichText's InlineSpan widgets to show just the matched words in blue and WidgetSpan widget to make the matched words tappable. Please see the code below or directly run it on DartPad https://dartpad.dev/c1fde787afc2792efd973752a7284d03

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Flutter Demo"),
        ),
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final List<InlineSpan> textSpans = [];
    final String text = "This is a #tag. This is #tag2. This is #tag3.";
    final RegExp regex = RegExp(r"\#(\w+)");
    final Iterable<Match> matches = regex.allMatches(text);
    int start = 0;
    for (final Match match in matches) {
      textSpans.add(TextSpan(text: text.substring(start, match.start)));
      textSpans.add(WidgetSpan(
          child: GestureDetector(
              onTap: () => print("You tapped #${match.group(1)}"),
              child: Text('#${match.group(1)}',
                  style: const TextStyle(color: Colors.blue)))));
      start = match.end;
    }
    textSpans.add(TextSpan(text: text.substring(start, text.length)));
    return Text.rich(TextSpan(children: textSpans));
  }
}

Solution 2

You can achieve the desired result using RegEx in only 2 lines:

List<String> extractHashtags(String text) {
  Iterable<Match> matches = RegExp(r"\B(\#[a-zA-Z]+\b)").allMatches(text);
  return matches.map((m) => m[0]).toList();
}

Solution 3

here is the code I wrote. haven't tested it but hope it works!

 List<String> hashAdder(String value) {
    List<String> tags = [];
    bool hashExist = value.contains('#');
    if (hashExist) {
      for (var i = 0; i < value.length; i++) {
        int hashIndex = value.indexOf('#');
        int hashEnd = value.indexOf(' ', hashIndex);
        tags.add(value.substring(hashIndex, hashEnd));
        value = value.substring(hashIndex);
      }
    }
    return tags;
  }

Solution 4

First, you can use split() method to get a list of words in your sentence. Then, you can check for each word in that list, and if that starts with #, then you can add that into the hashTag list. It will look like this:

    String s = "This is a #tag";
    List<String> splitted = s.split(" ");
    List<String> hashTags = List<String>();
    for (var item in splitted) {
      if (item.startsWith("#")) {
        hashTags.add(item);
      }
    }

    print(hashTags);
    // Expected output is: [#tag]

Share:
787
Lalit Rawat
Author by

Lalit Rawat

Updated on December 26, 2022

Comments

  • Lalit Rawat
    Lalit Rawat over 1 year

    I want to find out all the words which starts from #.

    For example = This is a #tag

    I want to create this(#tag) tappable and change its color to blue. Please advise something!

    Text("This is a #tag"),