Find substring

2 snippets across 2 stacks - Regular Expressions, SQL

Also written as locate substring

RXRegular Expressions

Literal Match

RX · Basic Patterns
Syntax
/hello/  or  r'hello'
Example
JS:  'say hello world'.match(/hello/)
Py:  re.search(r'hello', 'say hello world')
Output
Matches "hello" at index 4

Note Characters that are not special match themselves exactly. Regex is case-sensitive by default -- use the i flag for case-insensitive matching.

SQLSQL

POSITION / STRPOS

SQL · String Functions
Syntax
POSITION(substring IN string)
STRPOS(string, substring)  -- PostgreSQL
Example
SELECT
  email,
  POSITION('@' IN email) AS at_position,
  SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain
FROM users;
Output
-- email             | at_position | domain
-- [email protected] | 6           | example.com

Note Returns the 1-based position of the first occurrence. Returns 0 if not found (not -1 like most programming languages). MySQL uses LOCATE(substring, string) which has the arguments in reverse order.

Frequently asked questions

How do you find substring?
This task is covered in 2 stacks on this page: Regular Expressions, SQL. The "Literal Match" snippet in Regular Expressions uses `/hello/ or r'hello'`.
Which pattern does the Regular Expressions example use?
The "Literal Match" snippet uses `/hello/ or r'hello'`, from the Basic Patterns section of the Regular Expressions cheat sheet.
Which stacks cover "find substring" on this page?
Regular Expressions, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Literal Match": Characters that are not special match themselves exactly. Regex is case-sensitive by default -- use the i flag for case-insensitive matching.