2

I have strings of 010xxx, 011xxx, 110xxx, 111xxx, Q10xxx, Q11xxx in a field along with other values that are not similar. They might be XyzABC.

I have two regex patterns that separately give results that are good: [1Q]_[0-9]% and 0_[1-9]%

In words return true if

first letter is 1 or Q and the 3rd letter is a 0-9 

OR 

the first letter is 0 and the third letter is 1-9

How do I create a search pattern that does the OR either using SIMILAR TO or regex?

One version that works by itself is:

SELECT field FROM db WHERE field SIMILAR TO '[1Q]_[0-9]%'

Not wedded to SIMILAR or regex. They were just what I could get working until I tried to or them. Open to other suggestions.

1 Answer 1

3

You can use a SIMILAR TO pattern like

WHERE field SIMILAR TO '([1Q]_[0-9]|0_[1-9])%'

The SIMILAR TO pattern requires a full string match, so the pattern means: start with 1 or Q, then any char, then any digit, or start with 0, any char and a non-zero digit, and then there can be any 0 or more chars afterwards.

You can also use a regex like

WHERE field ~ '^(?:[1Q].[0-9]|0.[1-9])'

See the regex demo

Details:

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • [1Q].[0-9] - 1 or Q, any char and a digit
  • | - or
    • 0.[1-9] - 0, any char and a non-zero digit
  • ) - end of a non-capturing group.
Sign up to request clarification or add additional context in comments.

2 Comments

SIMILAR TO is internally converted to ~ automatically, so both versions are equally good.
Use the SIMILAR TO version and it worked. My problem was making the patter "readable" by putting spaces around the |. I was using regexplanet.com/advanced/postgresql/index.html for testing but will keep the other site in mind. Thanks. Up voted and marked as answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.