Trouble with Regex pattern

Options
arturosanz
arturosanz Member ✭✭
edited September 2023 in ? Transforming data

I'm trying to use the following regex pattern to validate phone numbers:

/+?\d{1,4}?[-.\s]?(?\d{1,3}?)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}/g

I works fine on https://regex101.com/

However, the regex_matches filter returns always false.

The same problem here. No matter what the input is, returns "the phone number is not valid".

Try +1 123 456 7890 for instance. The pattern works on regex101 but not on here.

Does anyone know why?

Tagged:

Best Answer

  • Cameron B
    Cameron B Member, Administrator

    ADMIN

    Answer ✓
    Options

    @devben you're totally right 😎

    @arturosanz As Dev said, when I ran inside my own tool (I like regexr.com) I received this error:

    I did use some community patterns, however, and this one worked remarkably well:

    /^\s*(?:+?(\d{1,3}))?([-. (](\d{3})[-. )])?((\d{3})[-. ](\d{2,4})(?:[-.x ](\d+))?)\s*$/g

Answers

  • Cameron B
    Cameron B Member, Administrator

    ADMIN

    Options

    For the regex engine to work properly the regex value needs to be encased within //, so that your regex reads as:

    /{regex}/

    Some engines and some regex require the use of adding a g at the end, to make it look like /{regex}/g - but you should be able to get it to work by adding the last slash in your expression. Mind giving that a go? Cheers!

  • devben
    devben Member
    Options

    @Cameron B

    It seems like he is already using forward slashes.

    @arturosanz

    I encountered an issue when trying your regex in regex101; specifically, the question marks appear to be non-quantifiable. You might want to consider the following regex pattern:

    ^([+]?\d{1,2}[-\s]?|)\d{3}[-\s]?\d{3}[-\s]?\d{4}$
    

    I also appreciate regex101 they offer a community library where you can search for regex patterns. Check it out here: regex101: Community Pattern Library

    If you're still facing difficulties, you could explore a custom JavaScript action and generate the code on the regex101 site.

    I hope this proves helpful.🙃

    Best regards,
    devben