Lookahead And Lookbehind Anchors

Validate several password rules with zero-width lookahead and slice dollar amounts with lookbehind, checking positions without consuming input characters.

JavaForm Validation

Code

snippet
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

FAQ

What does Lookahead And Lookbehind Anchors print when run?
Running the file directly is enough — expect labeled output lines such as `amount:`.