Examples of Regular Expressions |Python Java, JavaScript
Examples of Regular Expressions
Regular expressions are widely supported in programming languages such as Python, JavaScript, Java, and many others, making them a versatile tool for string manipulation tasks. At its core, a regular expression is a sequence of characters that define a search pattern. These patterns can include literal characters, metacharacters, and quantifiers, allowing you to match specific sequences of characters within a string.
1) Regular Expressions in Python
Let’s start with a simple example of using regular expressions in Python to match a specific pattern within a string:-
#Example 1: Matching a Pattern in a String
text = "The quick brown fox jumps over the lazy dog."
pattern = r'fox'
if re.search(pattern, text):
print("Pattern found!")
else:
print("Pattern not found.")
#Example 2: Extracting Email Addresses from a String
text = "Contact us at email@example.com or support@example.org"
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
email_addresses = re.findall(pattern, text)
print("Email addresses found:", email_addresses)
2) Regular Expressions in JavaScript
With the help of 02 quick examples, we can understand the regular expressions in JavaScript.
#Example 1: Matching a Pattern in a String
let text = "The quick brown fox jumps over the lazy dog.";
let pattern = /fox/;
if (pattern.test(text)) {
console.log("Pattern found!");
} else {
console.log("Pattern not found.");
}
#Example 2: Extracting Email Addresses from a String
let text = "Contact us at email@example.com or support@example.org";
let pattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
let emailAddresses = text.match(pattern);
console.log("Email addresses found:", emailAddresses);
3) Regular Expressions in Java
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
#Example 1: Matching a Pattern in a String
String text = "The quick brown fox jumps over the lazy dog.";
String pattern = "fox";
if (text.matches("." + pattern + ".")) {
System.out.println("Pattern found!");
} else {
System.out.println("Pattern not found.");
}
#Example 2: Extracting Email Addresses from a String
String text = "Contact us at email@example.com or support@example.org";
String pattern = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b";
Pattern emailPattern = Pattern.compile(pattern);
Matcher matcher = emailPattern.matcher(text);
while (matcher.find()) {
System.out.println("Email address found: " + matcher.group())
}
}
}
Conclusion
Experiment with different patterns and explore the vast capabilities of regular expressions to become a more proficient coder.
Related Blogs
Originally published at https://www.devstringx.com on April 04, 2024