Databricks Data Engineer Associate Question 161
Single answerYou are working with a Delta table containing a column named email_address, which stores email addresses in the format 'username@domain.com'. You need to extract only the domain part (e.g., 'domain.com') into a new column for further analysis. Which of the following code snippets correctly extracts the domain part?
- A
df.withColumn('domain', regexp_extract(col('email_address'), '@(.*)', 1))
- B
df.withColumn('domain', regexp_extract(col('email_address'), '.@(.)', 1))
- C
df.withColumn('domain', regexp_extract(col('email_address'), '@(.*)', 0))
- D
df.withColumn('domain', regexp_extract(col('email_address'), '.@(.)', 0))
Show answer and explanation
Correct answer: B
Explanation
The correct answer uses the regex '.@(.)', which matches everything before and after the '@', and correctly captures the domain part using group 1. The regexp_extract function retrieves the specified capture group, and the index must be 1 to extract only the domain.
- A. Incorrect.
This is incorrect because while the regex '@(.*)' correctly identifies the domain, the wrong capture group index (1) is used, which leads to an incorrect result.
- B. Correct.
This is correct because the regex '.@(.)' captures everything after '@', and the capture group index 1 retrieves the domain part.
- C. Incorrect.
This is incorrect because while the regex '@(.*)' is valid, the capture group index 0 retrieves the entire match, which includes the '@' and the domain, not just the domain.
- D. Incorrect.
This is incorrect because the capture group index 0 retrieves the entire match, which includes the username as well as the domain, rather than isolating the domain.