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.