Regex find all words exclude spaces and tabs (\n \t etc.)

Viewed 91

I'm trying to get all words from the string. They can include only letters and number. But I completely failed to exclude possible \n, \t etc.

So here is a test string:

word one of each one fish two fish red fish blue fish car : carpet as java : javascript!!&@$%^& testing, 1, 2 testing go Go GO Stop stop hello\nworld hello\tworld hello world \t\tIntroductory Course

I end up with this solution .

But
hello\nworld should be hello world
hello\tworld should be hello world
\t\tIntroductory Course should be Introductory Course

I had also tried solutions with \w \b and \S but I can't make them work as I want too.

How can I ignore/exclude \n and \t?

Thanks!

3 Answers

Pure regex:

(?:\\t|\\n)*([A-Za-z0-9]+)

PHP (with escaped \):

preg_match_all("/(?:\\\\t|\\\\n)*([A-Za-z0-9]+)/", $str, $matches);

Match only letters and numbers: \w. Check preg_match_all:

preg_match_all("/\w+/", $str, $matches);

If you are not acutally meaning tabs and newlines (with ascii code 9 and 10), then you can just remove the substrings '\n' and '\t' from the string first:

preg_match_all("/\w+/", str_replace(['\n', '\r'], ' ', $str), $matches);
Related