/* * [TestRegexNegative.java] * * Summary: Test Negative Regex. * * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2006-03-02 */ package com.mindprod.example; import java.util.regex.Pattern; import static java.lang.System.*; /** * Test Negative Regex. *

* Demonstrate how to use a negative regex, how to find strings that do NOT match a given Pattern. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2006-03-02 * @since 2006-03-02 */ public final class TestRegexNegative { /** * regex pattern that rejects strings of form "my connector is broken" but accepts "my anythingelse is broken". It * uses lookahead. You can't have a purely negative regex. You must have some sort of positive match. */ private static final Pattern pattern = Pattern.compile( "(?!my connector)my [\\p{Lower}]* is broken" ); /** * check negative regex * * @param args not used */ public static void main( String[] args ) { out.println( pattern.matcher( "my connector is broken" ).matches() );// false out.println( pattern.matcher( "my engine is broken" ).matches() );// true out.println( pattern.matcher( "my engine is working" ).matches() );// false } }