JavaScript: Step 11- Regular Expressions

image 2

Play Store Application link โ€“ Java to JavaScript in 13 Steps – App on Google Play


Regular expressions (regex or regexp) are patterns used to match combinations of characters within strings. They are particularly useful for search and replace operations. In JavaScript, regular expressions are objects that can be created using either the literal notation or the RegExp constructor.

Comparing to Core Java:

  • Core Java Comparison: In core Java, regular expressions are used via the Pattern and Matcher classes found in java.util.regex. These classes provide similar functionality to JavaScriptโ€™s regex, allowing for pattern matching and manipulation.

Tabular Comparisons:

FeatureJavaScriptCore Java
Literal Notation/pattern/Pattern.compile("pattern")
Constructor Notationnew RegExp('pattern')Pattern.compile("pattern")
Case-Insensitive/pattern/iPattern.compile("pattern", Pattern.CASE_INSENSITIVE)
Global Matching/pattern/gMatcher.find()
Multiline Matching/pattern/mPattern.compile("pattern", Pattern.MULTILINE)

Text Diagram:

String
  |
RegExp Object
  |
Pattern Matching

Basic Programs:

1. Matching a String Using a Regular Expression:

const pattern = /hello/;
const str = 'Hello, World!';
const result = pattern.test(str);
console.log(result); // false

Core Java Comparison: In Java, you would use Pattern and Matcher like this:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("hello");
        Matcher matcher = pattern.matcher("Hello, World!");
        boolean result = matcher.find();
        System.out.println(result); // false
    }
}

2. Using the exec() Method to Find Matches:

const pattern = /hello/g;
const str = 'Hello, World! Hello, JavaScript!';
let result;
while ((result = pattern.exec(str)) !== null) {
    console.log(result[0]);
}
// Output: "Hello" "Hello"

Core Java Comparison: Use Matcher.find() to achieve similar results:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher("Hello, World! Hello, JavaScript!");
        while (matcher.find()) {
            System.out.println(matcher.group()); // Output: "Hello" "Hello"
        }
    }
}

3. Replacing Text Using a Regular Expression:

const pattern = /hello/gi;
const str = 'Hello, World! Hello, JavaScript!';
const newStr = str.replace(pattern, 'Hi');
console.log(newStr); // "Hi, World! Hi, JavaScript!"

Core Java Comparison: Use Matcher.replaceAll() in Java:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher("Hello, World! Hello, JavaScript!");
        String newStr = matcher.replaceAll("Hi");
        System.out.println(newStr); // "Hi, World! Hi, JavaScript!"
    }
}

4. Validating User Input:

const pattern = /^[a-zA-Z\s]+$/;
const input = 'John Doe';
const isValid = pattern.test(input);
console.log(isValid); // true

Core Java Comparison: In Java, this is done with Pattern and Matcher as well:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("^[a-zA-Z\\s]+$");
        Matcher matcher = pattern.matcher("John Doe");
        boolean isValid = matcher.matches();
        System.out.println(isValid); // true
    }
}

5. Splitting a String Using a Regular Expression:

const pattern = /\s+/;
const str = 'Hello, World! How are you?';
const words = str.split(pattern);
console.log(words); // ["Hello,", "World!", "How", "are", "you?"]

Core Java Comparison: Splitting in Java can be done with String.split():

public class RegexExample {
    public static void main(String[] args) {
        String str = "Hello, World! How are you?";
        String[] words = str.split("\\s+");
        for (String word : words) {
            System.out.println(word);
        }
    }
}

Note: Regular expressions can be complex, and mastering them takes practice. The examples here provide a basic introduction to regex in JavaScript, with comparisons to core Java to aid understanding.

To run these JavaScript programs, create a .js file and execute it with Node.js or include the code in an HTML file and open it in a web browser.


Leave a Reply

Your email address will not be published. Required fields are marked *