如何找出字符串中以#开头的单词



我想找出所有以#开头的单词。

例如=这是一个#标签

我想创建这个(#tag(tapable并将其颜色更改为蓝色。请给我点建议!

Text("This is a #tag"),

使用RegEx只需两行即可实现所需结果:

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

您可以使用Regex查找所有以字符#开头的单词。然后使用Text.rich或RichText的InlineSpan小部件以蓝色显示匹配的单词,并使用WidgetSpan小程序使匹配的单词可点击。请参阅下面的代码或直接在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));
}
}

首先,您可以使用split((方法来获取句子中的单词列表。然后,您可以检查该列表中的每个单词,如果该单词以#开头,则可以将其添加到hashTag列表中。它看起来是这样的:

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]

这是我写的代码。还没有测试过,但希望它能起作用!

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;
}

最新更新