Regular Expressions (RegEx)
សេចក្តីផ្តើម
Regular Expressions (RegEx) គឺជា patterns ដែលប្រើសម្រាប់ស្វែងរក និងផ្គូផ្គង text។ វាមានប្រសិទ្ធភាពខ្ពស់សម្រាប់ validation និង searching។
RegEx Syntax
Pattern | ការពិពណ៌នា | ឧទាហរណ៍ |
---|---|---|
[abc] | តួអក្សរណាមួយក្នុងចំណោម | [aeiou] |
[0-9] | លេខណាមួយ | [0-9] |
(x|y) | x ឬ y | (cat|dog) |
\d | Digit (0-9) | \d{3} |
\w | Word character | \w+ |
\s | Whitespace | \s+ |
+ | One or more | a+ |
* | Zero or more | a* |
? | Zero or one | a? |
{n} | Exactly n times | a{3} |
Create RegEx
let pattern1 = /hello/;
let pattern2 = new RegExp("hello");
let pattern3 = /hello/i; // Case insensitive
វិធីបង្កើត regular expression
test() Method
let pattern = /hello/;
let result = pattern.test("hello world"); // true
ពិនិត្យថាតើ pattern ផ្គូផ្គងឬទេ
exec() Method
let pattern = /hello/;
let result = pattern.exec("hello world");
// Returns array with match info
ស្វែងរក និងយកព័ត៌មានអំពីការផ្គូផ្គង
String Methods
let str = "hello world";
str.match(/hello/); // Find matches
str.search(/world/); // Find position
str.replace(/world/, "JS"); // Replace
str.split(/\s+/); // Split by pattern
String methods ដែលប្រើ RegEx
Common Patterns
let email = /^[\w.-]+@[\w.-]+\.\w+$/;
let phone = /^\d{3}-\d{3}-\d{4}$/;
let url = /^https?:\/\/.+/;
Patterns ដែលប្រើញឹកញាប់
Flags
/pattern/g // Global (find all)
/pattern/i // Case insensitive
/pattern/m // Multiline
/pattern/gi // Combine flags
Flags សម្រាប់ modify behavior
Best Practices
- ប្រើ test() សម្រាប់ boolean checks
- ប្រើ exec() សម្រាប់ detailed info
- ចាំ escape special characters (\d, \w, \s)
- ប្រើ flags ត្រឹមត្រូវ (g, i, m)
- Test RegEx ជាមួយ tools online
សង្ខេប
- RegEx សម្រាប់ pattern matching
- Create: /pattern/ ឬ new RegExp()
- Methods: test(), exec()
- String methods: match(), search(), replace(), split()
- Flags: g (global), i (case-insensitive), m (multiline)