রেজেক্স মৌলিক চিটশিট
রেগুলার এক্সপ্রেশন (regex) এমন একটি প্যাটার্ন যা টেক্সটের সঙ্গে মেলে। প্রতিটি সিম্বল, যাকে টোকেন বলা হয়, প্যাটার্নের আচরণ বদলায়। নিচের চিটশিটে সবচেয়ে বেশি ব্যবহৃত টোকেন, তাদের সহজ অর্থ এবং কপি করে পরীক্ষা করা যায় এমন ছোট উদাহরণ দেওয়া হয়েছে।
| টোকেন | অর্থ | উদাহরণ |
|---|---|---|
| . | Matches any single character except newline. | a.c matches abc, a c |
| * | Matches the preceding token zero or more times. | ab* matches a, abb |
| + | Matches the preceding token one or more times. | ab+ matches ab, abb |
| ? | Makes the preceding token optional (zero or one). | colou?r matches color, colour |
| [] | Character set: matches any one character inside. | [aeiou] matches any vowel |
| [^] | Negated set: matches any character NOT inside. | [^0-9] matches any non-digit |
| \d | Matches any digit (0-9). | \d+ matches 42, 007 |
| \w | Matches any word character (a-z, A-Z, 0-9, _). | \w+ matches hello_1 |
| \s | Matches any whitespace (space, tab, newline). | a\sb matches a b |
| ^ | Anchors the match to the start of a line/string. | ^Hello matches start of string |
| $ | Anchors the match to the end of a line/string. | world$ matches end of string |
| | | Alternation: matches the pattern on either side. | cat|dog matches cat or dog |
| () | Groups a sub-pattern (and captures it). | (ab)+ matches ab, abab |
| {n,m} | Quantifier: match the preceding token n to m times. | a{2,4} matches aa, aaaa |
| (?i) | Inline flag: makes the pattern case-insensitive. | (?i)hello matches HELLO |
নোট
- বেশিরভাগ টোকেন ক্যারেক্টার সেট [ ]-এর ভেতরে তাদের বিশেষ অর্থ হারায়। যেমন [ ]-এর ভেতরে . শুধু একটি সাধারণ দাগের সঙ্গে মেলে।
- ব্যাকস্ল্যাশ (\) হল এস্কেপ ক্যারেক্টার: বিশেষ টোকেনকে সাধা ক্যারেক্টারে বদলায় এবং এর উল্টোটাও।
- ইঞ্জিন ভিন্ন হয়: Python, JavaScript, PCRE, Golang বেশিরভাগ টোকেন ভাগ করে নেয়, কিন্তু ফ্ল্যাগ ও look-around-এর সমর্থন আলাদা।
সচরাচর জিজ্ঞাসা
- ডট (.) কীসের সঙ্গে মেলে?
- ডিফল্টভাবে ডট নিউলাইন ছাড়া যেকোনো একটি ক্যারেক্টারের সঙ্গে মেলে। লিটারাল ডটের জন্য একে \ দিয়ে এস্কেপ করতে হবে।
- * ও + -এর মধ্যে পার্থক্য কী?
- অ্যাস্টারিস্ক * আগের টোকেনের সঙ্গে শূন্য বা তার বেশি বার মেলে, তাই 'ab*' 'a'-এর সঙ্গেও মেলে। প্লাস + কমপক্ষে একবার চায়, 'ab' মেলে কিন্তু শুধু 'a' নয়।
- সংখ্যা বা ওয়ার্ড ক্যারেক্টারের সঙ্গে কীভাবে মেলে?
- যেকোনো সংখ্যার (0-9) জন্য \d এবং ওয়ার্ড ক্যারেক্টারের (অক্ষর, সংখ্যা, আন্ডারস্কোর) জন্য \w ব্যবহার করুন। এদের নেতি হল \D ও \W।
- ^ ও $ কী করে?
- ^ মেলটিকে স্ট্রিং বা লাইনের শুরুতে এবং $ শেষে আটকায়। একসঙ্গে ^pattern$ পুরো স্ট্রিংয়ের মেল বাধ্যতামূলক করে।