Regex

Her er en stump tekst som kunne være et eksempel på noget input, hvor vi gerne vil finde alle telefonnumre.

Here is my number 123-456-7893.
Should you not be able to reach me there you can contact me at work (223)456-4305, or call my wife at 234.343.4521.

Opgaven med at finde telefonnumre kan i dette tilfælde løses ved at at bruge denne regular expression eller regex.

[\(]\*\d{3}[)-\.]\d{3}[\.-]\d{4}

Her er eksempel på hvordan det kan benyttes i javascript.

const re = /\(?\d{3}[)-\.]\d{3}[\.-]\d{4}/g;

const txt = `Here is my number 123-456-7893.
Should you not be able to reach me there you can contact me at work (223)456-4305, or call my wife at 234.343.4521.`;

const phoneNumbers = txt.match(re);
console.log(phoneNumbers);

Materiale

2.1: Introduction to Regular Expressions - Programming with Text

2.2: Regular Expressions: Meta-characters - Programming with Text

2.3: Regular Expressions: Character Classes - Programming with Text

2.4: Regular Expressions: Capturing Groups - Programming with Text

2.5: Regular Expressions: Back References - Programming with Text