Regex and JSON
Regex and JSON are common data processing tools. This lesson covers their usage in Java.
Regular Expressions
Regex is used for matching, searching, and replacing strings.
Basic Syntax
| Syntax | Description | Example |
|---|---|---|
. |
Any character | a.c matches "abc" |
\d |
Digit | \d+ matches "123" |
\w |
Word character | \w+ matches "hello_123" |
\s |
Whitespace | \s+ matches spaces/tabs |
^ |
Start | ^Hello matches start |
$ |
End | World$ matches end |
* |
0 or more | ab*c matches "ac", "abc" |
+ |
1 or more | ab+c matches "abc", "abbc" |
? |
0 or 1 | ab?c matches "ac", "abc" |
{n} |
n times | a{3} matches "aaa" |
{n,m} |
n to m times | a{2,4} matches "aa", "aaa" |
[] |
Character set | [abc] matches "a", "b", "c" |
| |
Or | cat|dog matches "cat" or "dog" |
() |
Group | (ab)+ matches "ab", "abab" |
Pattern and Matcher
JAVA
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexDemo {
public static void main(String[] args) {
String text = "My email is test@example.com, phone is 13812345678";
// Match email
Pattern emailPattern = Pattern.compile("\\w+@\\w+\\.\\w+");
Matcher emailMatcher = emailPattern.matcher(text);
if (emailMatcher.find()) {
System.out.println("Email: " + emailMatcher.group());
}
// Match phone
Pattern phonePattern = Pattern.compile("1[3-9]\\d{9}");
Matcher phoneMatcher = phonePattern.matcher(text);
if (phoneMatcher.find()) {
System.out.println("Phone: " + phoneMatcher.group());
}
}
}
Common Methods
JAVA
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexMethods {
public static void main(String[] args) {
String text = "Hello 123 World 456 Java 789";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
// find(): Find next match
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
System.out.println("Position: " + matcher.start() + "-" + matcher.end());
}
// matches(): Full match
System.out.println(Pattern.matches("\\d+", "123")); // true
System.out.println(Pattern.matches("\\d+", "123a")); // false
// split(): Split
String[] parts = "a,b,c".split(",");
for (String part : parts) {
System.out.println(part);
}
// replaceAll(): Replace all
String result = "Hello 123 World".replaceAll("\\d+", "***");
System.out.println(result); // Hello *** World
}
}
Example: Common Regex Patterns
JAVA
public class CommonRegex {
public static void main(String[] args) {
// Email validation
String emailRegex = "^[\\w.-]+@[\\w.-]+\\.\\w+$";
System.out.println(Pattern.matches(emailRegex, "test@example.com")); // true
// Phone validation
String phoneRegex = "^1[3-9]\\d{9}$";
System.out.println(Pattern.matches(phoneRegex, "13812345678")); // true
// ID card validation
String idCardRegex = "^\\d{17}[\\dXx]$";
System.out.println(Pattern.matches(idCardRegex, "11010119900101001X")); // true
// IP address validation
String ipRegex = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
System.out.println(Pattern.matches(ipRegex, "192.168.1.1")); // true
}
}
Group Capturing
JAVA
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupDemo {
public static void main(String[] args) {
String text = "2026-06-24";
Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
System.out.println("Full date: " + matcher.group(0)); // 2026-06-24
System.out.println("Year: " + matcher.group(1)); // 2026
System.out.println("Month: " + matcher.group(2)); // 06
System.out.println("Day: " + matcher.group(3)); // 24
}
}
}
JSON Processing
JSON is a lightweight data exchange format.
Manual JSON Parsing
JAVA
public class JsonParseDemo {
public static void main(String[] args) {
String json = "{\"name\":\"Alice\",\"age\":25,\"city\":\"Beijing\"}";
// Simple parsing (not recommended, use library in real projects)
json = json.replace("{", "").replace("}", "").replace("\"", "");
String[] pairs = json.split(",");
for (String pair : pairs) {
String[] kv = pair.split(":");
System.out.println(kv[0].trim() + " = " + kv[1].trim());
}
}
}
Using JSON Library (Jackson)
JAVA
// After adding Jackson dependency
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Object to JSON
User user = new User("Alice", 25, "Beijing");
String json = mapper.writeValueAsString(user);
System.out.println("JSON: " + json);
// {"name":"Alice","age":25,"city":"Beijing"}
// JSON to Object
User parsed = mapper.readValue(json, User.class);
System.out.println("Object: " + parsed);
}
}
class User {
private String name;
private int age;
private String city;
public User() {} // Jackson requires no-arg constructor
public User(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
// Getters/Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
@Override
public String toString() {
return "User{name='" + name + "', age=" + age + ", city='" + city + "'}";
}
}
JSON Arrays
JAVA
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class JsonArrayDemo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// JSON array
String json = "[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30}]";
// Parse to List
List<User> users = mapper.readValue(json, new TypeReference<List<User>>() {});
users.forEach(System.out::println);
// List to JSON
String result = mapper.writeValueAsString(users);
System.out.println(result);
}
}
Common JSON Operations
JAVA
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonNodeDemo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"Beijing\",\"zip\":\"100000\"}}";
// Parse to JsonNode
JsonNode node = mapper.readTree(json);
// Get values
System.out.println("name: " + node.get("name").asText());
System.out.println("age: " + node.get("age").asInt());
System.out.println("city: " + node.get("address").get("city").asText());
// Check existence
System.out.println("has email: " + node.has("email"));
}
}
String Regex Methods
JAVA
public class StringRegex {
public static void main(String[] args) {
String text = "Hello 123 World 456";
// matches(): Full match
System.out.println("123".matches("\\d+")); // true
// replaceAll(): Replace all matches
String result = text.replaceAll("\\d+", "***");
System.out.println(result); // Hello * World *
// replaceFirst(): Replace first match
String result2 = text.replaceFirst("\\d+", "***");
System.out.println(result2); // Hello *** World 456
// split(): Split
String[] parts = "a,b,,c".split(","); // Keep empty strings
System.out.println(parts.length); // 4
String[] parts2 = "a,b,,c".split(",", -1); // Keep trailing empty strings
System.out.println(parts2.length); // 4
}
}
❓ Frequently Asked Questions
Q Regex is hard to remember—what should I do?
A Remember common patterns: \d \w \s . * + ? [] (). For complex patterns, check documentation.
Q Which JSON library should I use in Java?
A Jackson is most popular. Gson is also good. For simple scenarios, manual parsing works.
Q How's regex performance?
A Simple regex performs well. Complex regex may have performance issues. Avoid too much backtracking.
📖 Summary
- Regex is used for string matching, searching, and replacing
- Pattern and Matcher are core classes for Java regex
- JSON is a lightweight data exchange format
- Jackson is Java's most popular JSON library
📝 Exercises
- Email validation: Write a method to validate email format
- Text extraction: Extract all links from HTML
- JSON parsing: Parse a JSON string and extract specific fields
Next Lesson
In the next lesson, we'll learn about Comprehensive Project — building a complete Java project.



