DEV Community

Cover image for 𝗛𝗼𝘄 𝘁𝗼 𝘂𝘀𝗲 𝗥𝗲𝗴𝗘𝘅 𝗶𝗻 𝗗𝗮𝗿𝘁?
Amr Azzam
Amr Azzam

Posted on

𝗛𝗼𝘄 𝘁𝗼 𝘂𝘀𝗲 𝗥𝗲𝗴𝗘𝘅 𝗶𝗻 𝗗𝗮𝗿𝘁?

It's used to match patterns in strings, allowing you to perform more complex string manipulations, validations, and extractions.

Here's a brief overview:
1- Creating a RegExp object:
Use the RegExp class to create a regular expression object. In Flutter, you can use this class to define patterns that you want to match.

𝘙𝘦𝘨𝘌𝘹𝘱 𝘮𝘺𝘙𝘦𝘨𝘌𝘹𝘱 = 𝘙𝘦𝘨𝘌𝘹𝘱(𝘳'𝘱𝘢𝘵𝘵𝘦𝘳𝘯');

Enter fullscreen mode Exit fullscreen mode

The r prefix before the string literal is used to denote a raw string.

2- Testing for a match:
Use the hasMatch method to check if a string contains a match for the regular expression.

𝘚𝘵𝘳𝘪𝘯𝘨 𝘮𝘺𝘚𝘵𝘳𝘪𝘯𝘨 = "𝘦𝘹𝘢𝘮𝘱𝘭𝘦 𝘵𝘦𝘹𝘵";
𝘪𝘧 (𝘮𝘺𝘙𝘦𝘨𝘌𝘹𝘱.𝘩𝘢𝘴𝘔𝘢𝘵𝘤𝘩(𝘮𝘺𝘚𝘵𝘳𝘪𝘯𝘨)) { 
𝘱𝘳𝘪𝘯𝘵("𝘔𝘢𝘵𝘤𝘩 𝘧𝘰𝘶𝘯𝘥!");
} 𝘦𝘭𝘴𝘦 {
𝘱𝘳𝘪𝘯𝘵("𝘕𝘰 𝘮𝘢𝘵𝘤𝘩 𝘧𝘰𝘶𝘯𝘥.");
Enter fullscreen mode Exit fullscreen mode

3- Finding matches:
Use the allMatches method to find all matches in a given string.

𝘚𝘵𝘳𝘪𝘯𝘨 𝘮𝘺𝘚𝘵𝘳𝘪𝘯𝘨 = "𝘦𝘹𝘢𝘮𝘱𝘭𝘦 𝘵𝘦𝘹𝘵 𝘸𝘪𝘵𝘩 𝘱𝘢𝘵𝘵𝘦𝘳𝘯 𝘱𝘢𝘵𝘵𝘦𝘳𝘯";
𝘓𝘪𝘴𝘵<𝘔𝘢𝘵𝘤𝘩> 𝘮𝘢𝘵𝘤𝘩𝘦𝘴 = 𝘮𝘺𝘙𝘦𝘨𝘌𝘹𝘱.𝘢𝘭𝘭𝘔𝘢𝘵𝘤𝘩𝘦𝘴(𝘮𝘺𝘚𝘵𝘳𝘪𝘯𝘨);
𝘧𝘰𝘳 (𝘔𝘢𝘵𝘤𝘩 𝘮𝘢𝘵𝘤𝘩 𝘪𝘯 𝘮𝘢𝘵𝘤𝘩𝘦𝘴) { 
𝘱𝘳𝘪𝘯𝘵("𝘔𝘢𝘵𝘤𝘩 𝘧𝘰𝘶𝘯𝘥 𝘢𝘵 ${𝘮𝘢𝘵𝘤𝘩.𝘴𝘵𝘢𝘳𝘵} - ${𝘮𝘢𝘵𝘤𝘩.𝘦𝘯𝘥}: ${𝘮𝘢𝘵𝘤𝘩.𝘨𝘳𝘰𝘶𝘱(0)}");
Enter fullscreen mode Exit fullscreen mode

4- Extracting matched groups:
If your regular expression contains groups, you can access them using the group method of the Match object.

𝘙𝘦𝘨𝘌𝘹𝘱 𝘮𝘺𝘙𝘦𝘨𝘌𝘹𝘱 = 𝘙𝘦𝘨𝘌𝘹𝘱(𝘳'(\𝘥{2})/(\𝘥{2})/(\𝘥{4})');
𝘚𝘵𝘳𝘪𝘯𝘨 𝘥𝘢𝘵𝘦𝘚𝘵𝘳𝘪𝘯𝘨 = "01/17/2024";
𝘔𝘢𝘵𝘤𝘩 𝘮𝘢𝘵𝘤𝘩 = 𝘮𝘺𝘙𝘦𝘨𝘌𝘹𝘱.𝘧𝘪𝘳𝘴𝘵𝘔𝘢𝘵𝘤𝘩(𝘥𝘢𝘵𝘦𝘚𝘵𝘳𝘪𝘯𝘨);
𝘪𝘧 (𝘮𝘢𝘵𝘤𝘩 != 𝘯𝘶𝘭𝘭) { 
𝘚𝘵𝘳𝘪𝘯𝘨 𝘥𝘢𝘺 = 𝘮𝘢𝘵𝘤𝘩.𝘨𝘳𝘰𝘶𝘱(1);
 𝘚𝘵𝘳𝘪𝘯𝘨 𝘮𝘰𝘯𝘵𝘩 = 𝘮𝘢𝘵𝘤𝘩.𝘨𝘳𝘰𝘶𝘱(2);
 𝘚𝘵𝘳𝘪𝘯𝘨 𝘺𝘦𝘢𝘳 = 𝘮𝘢𝘵𝘤𝘩.𝘨𝘳𝘰𝘶𝘱(3);
 𝘱𝘳𝘪𝘯𝘵("𝘋𝘢𝘵𝘦: $𝘮𝘰𝘯𝘵𝘩/$𝘥𝘢𝘺/$𝘺𝘦𝘢𝘳");
Enter fullscreen mode Exit fullscreen mode

5- Testing in a Flutter application:
You can use regular expressions in various scenarios in Flutter, such as form validations, parsing data, or filtering lists. For example, you might use a regular expression to validate an email address entered in a form.

𝘙𝘦𝘨𝘌𝘹𝘱 𝘦𝘮𝘢𝘪𝘭𝘙𝘦𝘨𝘌𝘹𝘱 = 𝘙𝘦𝘨𝘌𝘹𝘱(𝘳'^[\𝘸-]+(\.[\𝘸-]+)*@([\𝘸-]+\.)+[𝘢-𝘻𝘈-𝘡] {2,7}$');
𝘚𝘵𝘳𝘪𝘯𝘨 𝘦𝘮𝘢𝘪𝘭𝘈𝘥𝘥𝘳𝘦𝘴𝘴 = "𝘦𝘹𝘢𝘮𝘱𝘭𝘦@𝘦𝘮𝘢𝘪𝘭.𝘤𝘰𝘮";
𝘪𝘧 (𝘦𝘮𝘢𝘪𝘭𝘙𝘦𝘨𝘌𝘹𝘱.𝘩𝘢𝘴𝘔𝘢𝘵𝘤𝘩(𝘦𝘮𝘢𝘪𝘭𝘈𝘥𝘥𝘳𝘦𝘴𝘴)) {
𝘱𝘳𝘪𝘯𝘵("𝘝𝘢𝘭𝘪𝘥 𝘦𝘮𝘢𝘪𝘭 𝘢𝘥𝘥𝘳𝘦𝘴𝘴");
} 𝘦𝘭𝘴𝘦 {
 𝘱𝘳𝘪𝘯𝘵("𝘐𝘯𝘷𝘢𝘭𝘪𝘥 𝘦𝘮𝘢𝘪𝘭 𝘢𝘥𝘥𝘳𝘦𝘴𝘴");
Enter fullscreen mode Exit fullscreen mode

𝙒𝙖𝙞𝙩 𝙛𝙤𝙧 𝙩𝙝𝙚 𝙋𝙖𝙩𝙩𝙚𝙧𝙣𝙨 𝙤𝙛 𝙍𝙚𝙜𝙀𝙭 𝙥𝙤𝙨𝙩 🚀

Top comments (0)