1

I want to verify if the string began with name(followed by 3 digits) and ends with state.

My code did this

Actual Output: NOT, NOT, YES, YES, YES, YES, NOT.

Expected Output: NOT, NOT, NOT, NOT, NOT, YES, NOT

CREATE TABLE yourtable
("f1" varchar(19))
;

INSERT INTO yourtable
("f1")
VALUES
  ('name123/state/LA'),
  ('name123/state/LA/X1'),
  ('name1/state/'),
  ('nameabcccc/state/'),
  ('name3444/state/'),
  ('name444/state/'),
  ('name1/state/LA')
 ;

  SELECT f1,
  CASE when trim(f1) ~ '^name[^/]*/state\/$' then 'YES' ELSE 'NOT' END col2
  FROM yourtable
4
  • Your description doesn't match your code. Commented Aug 20, 2020 at 10:29
  • @LaurenzAlbe yes its giving bad results. look at the actual results and the expected ones Commented Aug 20, 2020 at 10:32
  • You are speaking of "tmp" and "x1", but your pattern has "name" and no "x1". Commented Aug 20, 2020 at 10:33
  • @Jappa What if value is like name344sdfdfd/state/? Commented Aug 20, 2020 at 10:46

1 Answer 1

3

starts with name (followed by 3 digits) and ends with state.

That's not what your regex does. You are missing a pattern for 3 digits and the / character doesn't need to be escaped.

The following will do what you exepct

trim(f1) ~ '^name[0-9]{3}[^0-9]*/state/$'

So the regex makes sure

  • the string starts with ^name
  • is followed by three digits [0-9]{3}
  • is followed by any other character except a digit [^0-9]*
  • ends with "/state/" by using /state/$
Sign up to request clarification or add additional context in comments.

Comments

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.