1

how would I be able to grab the number 2627995 from this string

"hellotest/2627995?hl=en"

I want to grab the number 2627995, here is my current regex but it does not work when I use regex extract from big query

(\/)\d{7,7}

SELECT
  REGEXP_EXTRACT(DESC, r"(\/)\d{7,7}")
  AS number
FROM
  `string table`

here is the output

error

Thank you!!

1
  • The slash is not a special character in regex: You neither need to use brackets (no need to capture it) nor escape it. ie \/ is identical to just / Commented Jun 24, 2021 at 5:16

3 Answers 3

1

I think you just want to match all digits coming after the last path separator, before either the start of the query parameter, or the end of the URL.

SELECT REGEXP_EXTRACT(DESC, r"/(\d+)(?:\?|$)") AS number
FROM `string table`

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

Try this one: r"\/(\d+)"

Comments

0

Your code returns the slash because you captured it (see the parentheses in (\/)\d{7,7}). REGEXP_EXTRACT only returns the captured substring.

Thus, you could just wrap the other part of your regex with the parentheses:

SELECT
  REGEXP_EXTRACT(DESC, r"/(\d{7})")
  AS number
FROM
  `string table`

NOTE:

  • In BigQuery, regex is specified with string literals, not regex literals (that are usually delimited with forward slashes), that is why you do not need to escape the / char (it is not a special regex metacharacter)
  • {7,7} is equal to {7} limiting quantifier, meaning seven occurrences.

Also, if you are sure the number is at the end of string or is followed with a query string, you can enhance it as

REGEXP_EXTRACT(DESC, r"/(\d+)(?:[?#]|$)")

where the regex means

  • / - a / char
  • (\d+) - Group 1 (the actual output): one or more digits
  • (?:[?#]|$) - either ? or # char, or end of string.

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.