दिन 23: असली Validation के लिए Regular Expressions
✅ आज आप सीखेंगे
- Regular expression क्या है और इसे कैसे पढ़ें
- Character classes, quantifiers, anchors
- Groups, alternation, named groups और flags
- Patterns के साथ test, match, matchAll, replace
- असली Indian validations – और regex कब न लें
🏢 असली दुनिया में
Sharma Sweets का B2B wholesale form दुकानों से orders लेता है। इसे दुकान का GSTIN, PIN code और कई formats में mobile number (+91 98290-12345, 09829012345, 98290 12345) चाहिए। if/else और indexOf से यह सैकड़ों lines है; regular expressions से हर एक की एक line – बस पढ़ना आना चाहिए।
Regular expression पढ़ना
const pin = /^[1-9][0-9]{5}$/; // Indian PIN code
console.log(pin.test('302003')); // true
console.log(pin.test('012345')); // false – cannot start with 0
console.log(pin.test('30200')); // false – only 5 digits
console.log(pin.test('302003a')); // false – $ means the string must end here| Token | किससे मेल | उदाहरण |
|---|---|---|
| \d / \D | अंक / अंक नहीं | \d{10} = दस अंक |
| \w / \s | अक्षर, अंक या _ / whitespace | \s+ = एक या अधिक spaces |
| [abc] / [^abc] | a, b, c में से एक / इनके अलावा | [A-Z] एक capital letter |
| . | नई line के अलावा कोई भी character | असली dot के लिए \. |
| * + ? | 0 या अधिक / 1 या अधिक / 0 या 1 | colou?r |
| {n} {n,} {n,m} | ठीक n / कम से कम n / n से m | \d{4,6} |
| ^ $ | Text की शुरुआत / अंत | पूरी value validation |
| \b | Word boundary | \bkaju\b |
| ( ) | | Group / OR | (milk|dry) |
| (? | Named group | (? |
असली Indian validations
const patterns = {
mobile: /^(?:\+?91[\s-]?|0)?[6-9]\d{4}[\s-]?\d{5}$/, // +91 98290-12345, 09829012345 …
pin: /^[1-9]\d{5}$/,
gstin: /^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$/, // 15 chars: state code + PAN + entity + Z + checksum
pan: /^[A-Z]{5}\d{4}[A-Z]$/,
ifsc: /^[A-Z]{4}0[A-Z0-9]{6}$/,
vehicle:/^[A-Z]{2}[ -]?\d{1,2}[ -]?[A-Z]{1,3}[ -]?\d{4}$/, // RJ 14 CX 1234
};
const tests = {
mobile: ['+91 98290-12345', '09829012345', '9829012345', '5829012345', '98290123'],
pin: ['302003', '102003', '002003'],
gstin: ['08ABCDE1234F1Z5', '08ABCDE1234F1X5'],
pan: ['ABCDE1234F', 'ABCD1234F'],
ifsc: ['SBIN0001234', 'SBIN1001234'],
vehicle: ['RJ 14 CX 1234', 'RJ14CX1234', 'R 14 CX 1234'],
};
for (const [name, values] of Object.entries(tests)) {
console.log(name.padEnd(8), values.map(v => `${v} ${patterns[name].test(v) ? '✅' : '❌'}`).join(' '));
}Regex सिर्फ़ आकार जाँचता है। 08ABCDE1234F1Z5 का GSTIN format सही है पर हो सकता है वह मौजूद न हो; mobile number बंद हो सकता है। असली verification के लिए checksum, OTP या server पर सरकारी API चाहिए। PAN या Aadhaar numbers तब तक कभी न रखें जब तक सच में ज़रूरी न हो और सहमति न हो।
पहले साफ़ करें, फिर validate
function normaliseMobile(input) {
const digits = input.replace(/\D/g, ''); // remove everything that is not a digit
const ten = digits.replace(/^(91|0)(?=\d{10}$)/, ''); // drop a leading 91 or 0 if 10 digits remain
return /^[6-9]\d{9}$/.test(ten) ? ten : null;
}
['+91 98290-12345', '(0) 98290 12345', '919829012345', '12345'].forEach(v => console.log(v.padEnd(18), '→', normaliseMobile(v)));
const pretty = n => n.replace(/^(\d{5})(\d{5})$/, '+91 $1 $2'); // $1, $2 = captured groups
console.log(pretty('9829012345'));खोजना, निकालना और बदलना
const sms = 'Order #1042 for ₹1,800 confirmed. Order #1043 for ₹650 pending. Call 98290 12345.';
console.log(/order #\d+/i.test(sms)); // i = case-insensitive
console.log(sms.match(/#\d+/g)); // g = all matches
for (const m of sms.matchAll(/#(?<id>\d+) for ₹(?<amount>[\d,]+) (?<status>\w+)/g)) {
const { id, amount, status } = m.groups; // named groups
console.log(id, Number(amount.replace(/,/g, '')), status);
}
console.log(sms.replace(/\d{5} \d{5}/, '***** *****')); // mask a phone number
console.log('kaju katli box'.replace(/\s+/g, ' ')); // collapse spaces
console.log('Ghewar,Rasmalai; Ladoo | Peda'.split(/\s*[,;|]\s*/));| Method | लौटाता है | उपयोग |
|---|---|---|
| regex.test(str) | true / false | Validation |
| str.match(regex) | पहला मेल (g से सभी), या null | Values निकालना |
| str.matchAll(regex /g) | Groups वाले matches का iterator | कई structured values निकालना |
| str.replace(regex, x) | नई string | साफ़, mask, format; $1 groups दर्शाता है |
| str.split(regex) | Array | कई separators पर बाँटना |
| new RegExp(text, "gi") | String से बना regex | Dynamic search (user input escape करें!) |
असली task: search शब्द सुरक्षित highlight
<input id="q" value="ka" placeholder="Search" aria-label="Search">
<ul id="list"></ul>
<script>
const items = ['Kaju Katli', 'Kalakand', 'Malai Ghewar', 'Besan Ladoo', 'Soan Papdi (1+1 offer)'];
const escape = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // treat user text literally
function render() {
const q = document.querySelector('#q').value.trim();
const list = document.querySelector('#list');
list.innerHTML = '';
const re = q ? new RegExp(`(${escape(q)})`, 'gi') : null;
for (const name of items) {
if (re && !name.match(re)) continue;
const li = document.createElement('li');
if (!re) { li.textContent = name; list.append(li); continue; }
name.split(re).forEach((part, i) => { // split keeps captured groups
const node = i % 2 ? document.createElement('mark') : document.createTextNode(part);
if (i % 2) node.textContent = part;
li.append(node);
});
list.append(li);
}
}
document.querySelector('#q').addEventListener('input', render);
render();
</script>HTML, JSON या पूरे e-mail RFC नियम regex से parse न करें। DOMParser, JSON.parse और साधारण e-mail जाँच (/^[^\s@]+@[^\s@]+\.[^\s@]+$/) व confirmation e-mail लें। Regex छोटे, commented और tested रखें।
🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
Solution देखें
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$/;
for (const p of ['sweets123', 'Sweets123', 'Sweets@123', 'S@1a']) {
console.log(p.padEnd(11), strong.test(p) ? 'strong ✅' : 'weak ❌');
}Solution देखें
const bill = 'Kaju Katli ₹1,800; Ghewar ₹650.50; Delivery ₹60; Discount -₹100';
const amounts = [...bill.matchAll(/(-?)₹([\d,]+(?:\.\d{1,2})?)/g)]
.map(m => (m[1] ? -1 : 1) * Number(m[2].replace(/,/g, '')));
console.log(amounts, 'Total:', amounts.reduce((a, b) => a + b, 0));Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
Indian mobile number कैसे validate करेंगे?
Non-digits और वैकल्पिक 91/0 prefix हटाकर साफ़ करें, फिर /^[6-9]\d{9}$/ जाँचें। ग़लत input पर दोस्ताना message दिखाएँ, और server पर OTP से मालिकाना जाँचें – सिर्फ़ format जाँच सबूत नहीं।
Greedy और lazy quantifiers क्या हैं?
Greedy quantifiers (*, +, {n,}) जितना हो सके उतना मेल करते हैं; ? जोड़ने (*?, +?) से lazy, जितना कम हो सके – जैसे /<.+?>/ पहले < और आख़िरी > के बीच सब की जगह एक tag से मेल खाता है।
सारांश
- Regex = classes, quantifiers, anchors और groups का pattern।
- पूरी value validation के लिए ^ … $; पहले input साफ़ करें।
- Validate को test, निकालने को matchAll/groups, साफ़ व mask करने को replace।
- User input escape करें; regex format जाँचता है, सच नहीं।
Day 24: higher-order functions, debounce और throttle – search boxes और scroll handlers तेज़ बनाएँ।
