search
HomeJavajavaTutorialCode Smell - Untested Regular Expressions

Regex Without Tests is Asking for Trouble - Don't be lazy. It is free with AI!

TL;DR: Use clear and concise regular expressions, and test them thoroughly.

Problems

  • Readability
  • No test cases
  • Missed edge cases
  • Debugging challenges
  • Unclear failures
  • Hidden defects

Solutions

  1. Ask your favorite AI to write test cases
  2. Break down complex regular expressions into smaller, more readable parts.
  3. Check edge cases
  4. Validate outputs
  5. Refactor regex once you created the tests
  6. Improve the Error Messages

Context

Regular expressions are powerful but tricky.

If you write a regex without tests, you're asking for unexpected errors.

If you write a cryptic regex and skip automated testing, you could miss important cases, causing security issues or user frustration.

Sample Code

Wrong

public class PasswordValidator {
    public static boolean isValidPassword(String password) {
        return password.matches(
            "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$");
        // This is a cryptic Regular Expression
    }
}

Right

import java.util.ArrayList;
import java.util.List;

public class PasswordValidator {
    public static List<string> validatePassword(String password) {
        List<string> errors = new ArrayList();

        if (password.length()  result = 
            PasswordValidator.validatePassword(
            "StrongPass1");
        assertEquals("Password is valid.", result.get(0));
    }

    @Test
    public void testTooShortPassword() {
        List<string> result = PasswordValidator.validatePassword(
            "Short1");
        assertTrue(result.contains(
            "Password must be at least 8 characters long."));
    }

    @Test
    public void testNoUppercase() {
        List<string> result = PasswordValidator.validatePassword(
            "nouppercase1");
        assertTrue(
            result.contains(
                "Password must contain at least one uppercase letter."));
    }

    @Test
    public void testNoLowercase() {
        List<string> result = PasswordValidator.validatePassword(
            "NOLOWERCASE1");
        assertTrue(result.contains(
            "Password must contain at least one lowercase letter."));
    }

    @Test
    public void testNoNumber() {
        List<string> result = PasswordValidator.validatePassword(
            "NoNumberPass");
        assertTrue(result.contains(
            "Password must contain at least one digit."));
    }
}
</string></string></string></string></string></string>

Detection

[X] Automatic

You can detect when your regex is uncovered by changing it to fail and running all your tests.

If your validation returns "false" without user-friendly explanations, it's a clear sign you need to refactor it and improve the feedback.

Tags

  • Testing

Level

[X] Beginner

AI Generation

AI can generate regular expressions but often fails to provide helpful error messages.

Without proper instructions, AI-generated validators may fail to guide users through fixing their inputs.

AI Detection

AI can detect basic regular expression patterns and missing feedback with clear prompting.

it might not automatically create detailed test cases or descriptions unless asked specifically.

Try Them!

Remember: AI Assistants make lots of mistakes

Without Proper Instructions With Specific Instructions
ChatGPT ChatGPT
Claude Claude
Perplexity Perplexity
Copilot Copilot
Gemini Gemini

Conclusion

A regular expression without clear feedback is user-unfriendly and prone to errors.

It would help if you described why they failed and wrote thorough tests to ensure your regex works as expected.

Relations

Disclaimer

Code Smells are my opinion.

Credits

Photo by rc.xyz NFT gallery on Unsplash


Feedback is the breakfast of champions.

Ken Blanchard


This article is part of the CodeSmell Series.

The above is the detailed content of Code Smell - Untested Regular Expressions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment