Lookahead And Lookbehind Anchors
Validate several password rules with zero-width lookahead and slice dollar amounts with lookbehind, checking positions without consuming input characters.
Code
import java.util.regex.Pattern;
public class PasswordRules {
// lookahead (?=...) / lookbehind (?<=...):零宽断言只检查位置,不消耗字符。
// 多条规则因此能叠在同一个起点上逐条把关
static final Pattern STRONG = Pattern.compile(
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\w]).{10,}$");
// 后行断言把 $ 留在原文里,捕获组只装真正的金额
static final Pattern AMOUNT = Pattern.compile("(?<=\\$)\\d+(?:\\.\\d{2})?");
public static void main(String[] args) {
System.out.println(STRONG.matcher("Tr0ub4dor&xx").matches());
System.out.println(STRONG.matcher("alllowercase1!").matches());
String page = "refund $42.50, credit $7, tax $129.99";
AMOUNT.matcher(page).results()
.forEach(m -> System.out.println("amount: " + m.group()));
}
}How it works
Count the class PasswordRules and the function main as the entire surface area of Lookahead And Lookbehind Anchors.
Putting it to use
Running the file prints labeled results such as amount: — each operation’s effect is visible in the output.
Core lines
static final Pattern AMOUNT = Pattern.compile("(?<=\\$)\\d+(?:\\.\\d{2})?");
String page = "refund $42.50, credit $7, tax $129.99";
AMOUNT.matcher(page).results()
.forEach(m -> System.out.println("amount: " + m.group()));
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.
FAQ
- What does Lookahead And Lookbehind Anchors print when run?
- Running the file directly is enough — expect labeled output lines such as `amount:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.