Warm‑up: Extract orderId + amount using capturing groups (with answer)
Warm‑up: Input is a single log line: "Order[ORD-α1✅] paid ₹1200.50 by user='Gopi Suresh'" Task: 1) Use a regex with capturing groups to extract: - orderId (inside Order[...]) - amount (number with optional decimal) 2) Print both values. Implement ONLY: warmUp()
import java.util.regex.*;
public class Main {
// ✅ TODO: Student must implement only this method
static void warmUp() {
// TODO:
// - define log line
// - build Pattern with groups: Order\[(...)] and amount
// - use Matcher.find()
// - print orderId and amount
throw new UnsupportedOperationException("TODO");
}
public static void main(String[] args) {
warmUp();
}
}
Answer (Logic + Code)
Logic: - Pattern compiles the regex. - Matcher scans the input. - Parentheses (...) create capturing groups accessible via group(1), group(2).
static void warmUp() {
String log = "Order[ORD-α1✅] paid ₹1200.50 by user='Gopi Suresh'";
Pattern p = Pattern.compile("Order\[(.+?)]\s+paid\s+[^0-9]*([0-9]+(?:\.[0-9]+)?)");
Matcher m = p.matcher(log);
if (m.find()) {
String orderId = m.group(1); // group1 = inside Order[...]
String amount = m.group(2); // group2 = numeric amount
System.out.println(orderId);
System.out.println(amount);
} else {
System.out.println("No match");
}
}