[JavaScript]Basics of Regular Expressions – Pattern Matching and Metacharacter List

目次

Overview

Regular Expressions (RegExp) are a powerful syntax for describing “patterns” within strings. They allow you to implement complex logic—such as determining if specific keywords exist or validating the format of phone numbers and email addresses—with shorter and more efficient code than listing multiple if (str.includes(...) || str.includes(...)) statements. This article explains how to implement device detection based on browser information and provides a comprehensive list of major metacharacters.

Specifications (Input/Output)

  • Input: Browser user agent information (navigator.userAgent).
  • Output: Detection result of whether the current device is “iOS,” “Android,” or “Other.”
  • Operation: * Retrieves the user agent when the page loads.
    • Uses a regular expression to determine the OS.
    • Displays the result on the screen.

Basic Usage

In JavaScript, you create a regular expression literal by wrapping a pattern in slashes: /pattern/. You then use the test() method to perform matching, which returns true or false.

const str = "Apple iPhone 15";
const pattern = /iPhone|iPad/; // Matches iPhone OR iPad

if (pattern.test(str)) {
    console.log("This is an iOS device");
}

Regular Expression Pattern List

Below are commonly used metacharacters and their meanings.

PatternMeaningExample Matches
xThe character “x” itselfx
xyzThe sequence “xyz”xyz
[xyz]Any one character among x, y, or zx, y, z
[a-z]Any one character in the range a to za, j, z
[^xyz]Any one character EXCEPT x, y, or z (negation)a, 1
[^a-z]Any one character OUTSIDE the range a to z1, A
abc|xyzMatches “abc” OR “xyz”abc, xyz
{3}Exactly 3 occurrences of the preceding characteraaa (for a{3})
^xMatches “x” only at the beginning of the stringx...
x$Matches “x” only at the end of the string...x
.Any single character except for newlinesa, 1, %
x*Matches “x” 0 or more times(empty), x, xx
\Escapes the following metacharacter\. matches a literal dot
\dAny digit [0-9]0, 9
\DAny character that is NOT a digit [^0-9]a, $
\wAlphanumeric characters and underscores [A-Za-z0-9_]a, 1, _
\sWhitespace characters (space, tab, newline), \t, \n
\SAny character that is NOT whitespacea, 1
\tTab character(tab)
\nNewline character(newline)

Full Code (HTML / JavaScript)

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>UserAgent Regex Test</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .result-box {
            padding: 15px;
            background-color: #f0f0f0;
            border-left: 5px solid #007bff;
            margin-top: 10px;
        }
        .ua-text { font-size: 0.8em; color: #666; margin-bottom: 10px; display: block;}
        .os-label { font-weight: bold; font-size: 1.2em; }
        .ios { color: #e91e63; }
        .android { color: #4caf50; }
        .pc { color: #2196f3; }
    </style>
</head>
<body>

    <h2>OS/Device Detection Tool</h2>
    
    <div class="result-box">
        <span class="ua-text" id="uaDisplay">UserAgent: Retrieving...</span>
        <div id="resultDisplay" class="os-label">Analyzing...</div>
    </div>

    <script src="app.js"></script>
</body>
</html>

JavaScript (app.js)

/**
 * Get references to HTML elements
 */
const uaDisplay = document.getElementById("uaDisplay");
const resultDisplay = document.getElementById("resultDisplay");

/**
 * Function to analyze the UserAgent and display the result
 */
const detectDevice = () => {
    // Retrieve the browser's UserAgent string
    const ua = navigator.userAgent;
    
    // Display the UserAgent on screen (for verification)
    uaDisplay.textContent = `UserAgent: ${ua}`;

    // Detection Logic
    // 1. iOS Detection: Check for iPhone, iPod, or iPad
    // The "i" flag makes the pattern case-insensitive
    if (/iPhone|iPod|iPad/i.test(ua)) {
        resultDisplay.textContent = "Detected OS: iOS (iPhone/iPad)";
        resultDisplay.className = "os-label ios";
        return;
    }

    // 2. Android Detection: Check for Android
    if (/Android/i.test(ua)) {
        resultDisplay.textContent = "Detected OS: Android";
        resultDisplay.className = "os-label android";
        return;
    }

    // 3. Other (Mainly PC)
    resultDisplay.textContent = "Detected OS: PC / Other";
    resultDisplay.className = "os-label pc";
};

// Execute
detectDevice();

Tips for Customization

  • Using Flags: You can modify how a regular expression works by adding flags after the closing slash.
    • /abc/i: Case-insensitive (ignores the difference between “A” and “a”).
    • /abc/g: Global search (finds all matches instead of just the first one).
  • Strict Matching: Combining ^ (start) and $ (end) allows you to check if a string matches a pattern exactly.
    • Example: /^\d{3}-\d{4}$/.test(zipCode) (validates a specific postal code format).

Important Notes

  • Escaping Special Characters: If you need to search for a literal dot ., parenthesis (, or other metacharacters as normal text, you must prefix them with a backslash \ (e.g., \.).
  • Maintainability: Complex regular expressions can become hard to read. It is best practice to include comments or break down very long patterns into smaller variables for clarity.

Advanced Application

Validating Zip Code Formats

This example checks if a string consists specifically of three digits, a hyphen, and four digits.

const zipCode = "123-4567";

// ^     : Start of string
// \d{3} : Exactly three digits
// -     : A literal hyphen
// \d{4} : Exactly four digits
// $     : End of string
const isValidZip = /^\d{3}-\d{4}$/.test(zipCode);

console.log(isValidZip); // true

Conclusion

Regular Expressions are a powerful tool that can replace redundant chains of includes() with a single line of code for pattern detection and format validation. By mastering basic metacharacters like | (OR), \d (digit), and anchors like ^ $, you can significantly improve the efficiency of your input validation and string processing tasks.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次