forked from Iamstanlee/linkfy_text
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regex.dart
72 lines (66 loc) · 2.2 KB
/
regex.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import 'package:linkfy_text/src/enum.dart';
// String urlRegExp =
// url regex that accept https, http, www
String urlRegExp =
r'((https?://)?(www\.)?[a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))';
String hashtagRegExp = r'(#+[a-zA-Z0-9(_)]{1,})';
String userTagRegExp = r'(?<![\w@])@([\w@]+(?:[.!][\w@]+)*)';
String phoneRegExp =
r'\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*';
String emailRegExp =
r"([a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+)";
/// construct regexp. pattern from provided link types
RegExp constructRegExpFromLinkType(List<LinkType> types) {
// default case where we always want to match url strings
final len = types.length;
if (len == 1 && types.first == LinkType.url) {
return RegExp(urlRegExp);
}
final buffer = StringBuffer();
for (var i = 0; i < len; i++) {
final type = types[i];
final isLast = i == len - 1;
switch (type) {
case LinkType.url:
isLast ? buffer.write("($urlRegExp)") : buffer.write("($urlRegExp)|");
break;
case LinkType.hashTag:
isLast
? buffer.write("($hashtagRegExp)")
: buffer.write("($hashtagRegExp)|");
break;
case LinkType.userTag:
isLast
? buffer.write("($userTagRegExp)")
: buffer.write("($userTagRegExp)|");
break;
case LinkType.email:
isLast
? buffer.write("($emailRegExp)")
: buffer.write("($emailRegExp)|");
break;
case LinkType.phone:
isLast
? buffer.write("($phoneRegExp)")
: buffer.write("($phoneRegExp)|");
break;
default:
}
}
return RegExp(buffer.toString());
}
LinkType getMatchedType(String match) {
late LinkType type;
if (RegExp(emailRegExp).hasMatch(match)) {
type = LinkType.email;
} else if (RegExp(phoneRegExp).hasMatch(match)) {
type = LinkType.phone;
} else if (RegExp(userTagRegExp).hasMatch(match)) {
type = LinkType.userTag;
} else if (RegExp(urlRegExp).hasMatch(match)) {
type = LinkType.url;
} else if (RegExp(hashtagRegExp).hasMatch(match)) {
type = LinkType.hashTag;
}
return type;
}