Skip to content

Using ChatGPT to Explain RegEx

I have generally been unimpressed with AI as a coding assistant, at least where it’s built into my IDE. (My experimenting as been with GitHub Co-Pilot and ChatGPT).

Sometimes it works well, and can really impress you. But often, I’ve found the suggestions either be totally wrong – making up functions that don’t exist, not following coding standards, etc.

But I did find one thing that it does seem to be useful for – reverse engineering a regular expression (to explain what a regular expression means, in English).

Here’s an example I tried:

Prompt (to ChatGPT)

Explain PHP RegEx /^(?=.[0-9])(?=.[A-Z]).{8,}$

Response

The PHP regular expression you provided:

/^(?=.*[0-9])(?=.*[A-Z]).{8,}$/

Breaks down as follows:

  • ^: Asserts the start of the string.
  • (?=.*[0-9]): Positive lookahead assertion. It asserts that somewhere in the string there is at least one numeric character ([0-9]).
  • (?=.*[A-Z]): Positive lookahead assertion. It asserts that somewhere in the string there is at least one uppercase alphabetic character ([A-Z]).
  • .{8,}: Matches any character (except newline) at least 8 times ({8,}). This ensures that the total length of the string is at least 8 characters.
  • $: Asserts the end of the string.

Therefore, this regular expression ensures that the string:

  • Contains at least one numeric character.
  • Contains at least one uppercase alphabetic character.
  • Has a minimum length of 8 characters.

It can be used, for example, to validate passwords to ensure they meet certain complexity requirements, such as having a mix of numbers and uppercase letters and being of a certain length.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.