preg_split
preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array|false
Splits a string using a regular expression as the delimiter.
C C23
C23
#include <regex.h>
#include <stdio.h>
int main(void) {
regex_t re;
regcomp(&re, "[[:space:]]+", REG_EXTENDED);
const char *s = "a b c";
int first = 1;
const char *cur = s;
regmatch_t m[1];
while (regexec(&re, cur, 1, m, 0) == 0) {
printf(first ? "%.*s" : "|%.*s", (int)m[0].rm_so, cur);
first = 0;
cur += m[0].rm_eo;
}
printf(first ? "%s" : "|%s", cur);
printf("\n");
regfree(&re);
return 0;
}
Output
a|b|c
C++ C++26
C++26
#include <iostream>
#include <regex>
#include <string>
#include <vector>
int main() {
std::string s = "a b c";
std::regex re(R"(\s+)");
// -1 means split at the match points (keeping the non-matching segments)
std::sregex_token_iterator it(s.begin(), s.end(), re, -1), end;
bool first = true;
for (; it != end; ++it) {
if (!first) std::cout << "|";
std::cout << *it;
first = false;
}
std::cout << "\n";
return 0;
}
Output
a|b|c
C# v11.0.100
v11.0.100
var parts = System.Text.RegularExpressions.Regex.Split("a b c", @"\s+");
Console.WriteLine(string.Join("|", parts));
Output
a|b|c
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
re := regexp.MustCompile(`\s+`)
fmt.Println(strings.Join(re.Split("a b c", -1), "|"))
}
Output
a|b|c
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
System.out.println(String.join("|", "a b c".split("\\s+")));
}
}
Output
a|b|c
JavaScript v26.13.1
v26.13.1
console.log("a b c".split(/\s+/).join("|"))
Output
a|b|c
PHP v8.6.0
v8.6.0
echo implode("|", preg_split('/\s+/', "a b c"));
Output
a|b|c
Python v3.15.2
v3.15.2
import re
print("|".join(re.split(r"\s+", "a b c")))
Output
a|b|c
Rust v1.99.1
v1.99.1
fn main() {
// split by regex, collect, then join for display
let re = regex::Regex::new(r"\s+").unwrap();
let parts: Vec<&str> = re.split("a b c").collect();
println!("{}", parts.join("|"));
}
Output
a|b|c
TypeScript v26.13.1
v26.13.1
console.log("a b c".split(/\s+/).join("|"));
Output
a|b|c
Language differences
C: has no built-in containers or higher-order functions; the example advances through regex match offsets and splits the string with pointers.
Go: regexp.Split.
Java: String.split; Java split drops trailing empty strings.
JavaScript: String.split (accepts a regex).
PHP: every language supports regex-based splitting — preg_split.
Python: re.split.
Rust: splits with regex::split, which returns an iterator (collected here); equivalent to PHP preg_split.