Splitting and extracting
Split text on a pattern, see capture groups leak into the result, split at zero-width positions, and tokenize with match, matchAll and findall.
Splitting and extracting
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- split cuts text at every match of the separator and returns the pieces between. A regex separator handles variable delimiters, like /[,;\s]+/ for commas, semicolons and runs of whitespace.
- Leading and trailing delimiters produce empty strings: ',a,,b,'.split(',') gives ['', 'a', '', 'b', '']. Use a + in the separator, trim first or filter(Boolean).
- Capturing groups in the separator are added to the output, and an unmatched group adds undefined (None in Python). Use (?:...) if you want the pieces only.
- A zero-width separator splits without removing anything: 'camelCase'.split(/(?=[A-Z])/) gives ['camel', 'Case'].
- Split when you know what separates the pieces. Extract with match, matchAll, findall or finditer when you know what the pieces look like. A tokenizer is extraction with alternatives.
Two ways to cut a string
You have a, b;c d and want the four letters. The separators are inconsistent: a comma and space, a semicolon, two spaces. Plain split(',') only knows one fixed separator. A regex can describe “any of these, one or more times”.
There are two views of the same job. Splitting says “I know what separates the pieces” and cuts there. Extracting says “I know what the pieces look like” and collects those. You pick the view that matches what you know.
Splitting on a pattern
'a, b;c d'.split(/[,;\s]+/) // [ 'a', 'b', 'c', 'd' ]
'a, b'.split(',') // [ 'a', ' b' ]
'a, b'.split(/\s*,\s*/) // [ 'a', 'b' ]
The + is important. It makes a run of separators count as one cut. Without it you get empty strings between neighbouring delimiters, and delimiters at the edges produce them too:
',a,,b,'.split(',') // [ '', 'a', '', 'b', '' ]
',a,,b,'.split(/,+/) // [ '', 'a', 'b', '' ]
',a,,b,'.split(/,+/).filter(Boolean) // [ 'a', 'b' ]
' a b '.split(/\s+/) // [ '', 'a', 'b', '' ]
' a b '.trim().split(/\s+/) // [ 'a', 'b' ]
Each separator match belongs to neither neighbour, so a delimiter at the very start has “nothing” before it, and that nothing is an empty string. trim first, or filter the empties out afterwards. A second argument limits the count: 'a1b2c3'.split(/\d/, 2) returned ['a', 'b']. Note that JavaScript’s limit truncates the result rather than leaving the remainder in the last piece. Python’s maxsplit works the other way: re.split(r'\d', 'a1b2c3', maxsplit=2) gave ['a', 'b', 'c3'].
Line endings are the everyday case: 'a\r\nb\nc'.split(/\r?\n/) returned ['a', 'b', 'c'], while split('\n') left a stray \r on the first piece.
Captures leak into the result
The non-capturing groups lesson showed that capture groups change what split returns. Here it is again, because it surprises people more than once:
'x=42+y'.split(/[=+]/) // [ 'x', '42', 'y' ]
'x=42+y'.split(/([=+])/) // [ 'x', '=', '42', '+', 'y' ]
'a1b'.split(/(x)?\d/) // [ 'a', undefined, 'b' ]
With a capturing group, the separators come back in the array, which is useful for tokenizing: you keep both the operands and the operators. The third line shows the side effect. The group (x)? didn’t take part, and undefined went into the array anyway. Python’s re.split(r'(x)?\d', 'a1b') gave ['a', None, 'b']. Use (?:...) when you want grouping without that.
Splitting at a position
A zero-width separator removes nothing. Using a lookahead, you cut between characters:
'camelCaseWordHTTP'.split(/(?=[A-Z])/)
// [ 'camel', 'Case', 'Word', 'H', 'T', 'T', 'P' ]
'1234567'.split(/(?=(?:\d{3})+$)/)
// [ '1', '234', '567' ]
The first breaks before every capital, which works for camelCase and misfires on acronyms, as you can see: HTTP became four letters. Python 3.9 does the same, re.split(r'(?=[A-Z])', 'camelCaseWord') returned ['camel', 'Case', 'Word']. Python 3.9 also splits on empty matches in general, so re.split(r'x*', 'axbc') gave ['', 'a', '', 'b', 'c', ''], which is rarely what you meant. One more: '😀a'.split('') produced a broken pair of surrogate halves and then a, but '😀a'.split(/(?:)/u) produced ['😀', 'a']. The u flag from the flags lesson matters here.
Extracting instead
When the pieces have a shape, describe them and skip the separators:
'a,b,,c'.split(',') // [ 'a', 'b', '', 'c' ]
'a,b,,c'.match(/[^,]+/g) // [ 'a', 'b', 'c' ]
The second one never produces an empty field, because empty fields don’t match “one or more non-commas”. That’s the negated class from the earlier lessons doing its usual work.
Tokenizing: extraction with alternatives
A tokenizer turns total = 42 + rate*7 into words, numbers and operators. Alternation does the job, with one alternative per kind:
src.match(/\d+|[a-z]+|[=+*\/-]/g)
// [ 'total', '=', '42', '+', 'rate', '*', '7' ]
To also learn the kind, use named groups with matchAll. Exactly one group holds text per match, and the others are undefined:
const tok = /(?<num>\d+)|(?<id>[a-z]+)|(?<op>[=+*\/-])/g;
[...src.matchAll(tok)].map(m => {
const [type, value] = Object.entries(m.groups).find(([, v]) => v !== undefined);
return `${type}:${value}`;
})
// [ 'id:total', 'op:=', 'num:42', 'op:+', 'id:rate', 'op:*', 'num:7' ]
Python spells this with re.finditer and m.lastgroup, the name of the last matched group, which was [('id', 'total'), ('op', '='), ('num', '42'), ...]. re.findall(r'\d+|[a-z]+|[=+*/-]', ...) returned the plain list, since it has no capturing groups. A split with a capturing separator got the same tokens here, src.split(/\s*([=+*\/-])\s*/), though it only works when every token is either an operator or sits between operators. The shell can do the extraction view too: grep -oE '[0-9]+|[a-z]+|[=+*/-]' printed the seven tokens one per line, and sed -E 's/[,; ]+/\n/g' split a, b;c d into four lines. The grep lesson explains -o.
About the video
The embedded video is The Coding Train’s “2.8: Regular Expressions: split() - Programming with Text”, published 19 September 2016 and 9 minutes 2 seconds long. The description says it covers split() as a JavaScript string function that breaks text into tokens at a delimiter defined by a regular expression. It has no chapters. It is JavaScript. I couldn’t read a transcript, so I can’t say whether it mentions the captured-separator behaviour, and the zero-width splitting, matchAll tokenizer and Python material above are my own runs. English per its title and description.
What I did not run
GNU tools, split with a sticky regex, and locale-aware splitting through Intl.Segmenter.
Next
Python has its own entry points, and search, match and fullmatch mean different things. Regex in Python walks through them.
Check yourself
'x=42+y'.split(/([=+])/) returns five items. Why, and how do you get three?
The parentheses capture the separator and split puts captured text into the result, giving ['x', '=', '42', '+', 'y']. Remove the group or make it non-capturing, /[=+]/ or /(?:[=+])/, to get ['x', '42', 'y'].
How would you split a camelCase name into words in JavaScript?
name.split(/(?=[A-Z])/). The lookahead matches the empty position before each capital without consuming it, so no characters are lost. 'camelCaseWordHTTP' becomes ['camel', 'Case', 'Word', 'H', 'T', 'T', 'P'], so acronyms need extra handling.
When is extracting better than splitting for a comma list like 'a,b,,c'?
When you want only non-empty fields. split(',') returns ['a', 'b', '', 'c'], while match(/[^,]+/g) returns ['a', 'b', 'c']. Extraction describes the thing you want, so empty fields never appear.
What do you use in Python to tokenize a string and learn which alternative matched?
re.finditer with named groups and m.lastgroup. With (?P<num>\d+)|(?P<id>[a-z]+)|(?P<op>[=+*/-]) it returned pairs like ('id', 'total') and ('num', '42').
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.