正则表达式查找所有单词,排除空格和制表符(\ n \ t等)

时间:2018-09-18 21:24:43

标签: php regex

我正在尝试从字符串中获取所有单词。它们只能包含字母和数字。但是我完全无法排除可能的\ n,\ t等。

这是一个测试字符串:

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

我最终得到this solution

但是
hello\nworld应该是hello world
hello\tworld应该是hello world
\t\tIntroductory Course应该是Introductory Course

我也尝试过使用\ w \ b和\ S的解决方案,但是我也无法使它们按我的意愿工作。

如何忽略/排除\ n和\ t?

谢谢!

3 个答案:

答案 0 :(得分:1)

纯正则表达式:

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

PHP(使用转义的\):

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

答案 1 :(得分:0)

仅匹配字母和数字:\w。选中preg_match_all

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

如果您并非非要使用制表符和换行符(ASCII代码分别为9和10),则只需先从字符串中删除子字符串'\n''\t'

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

答案 2 :(得分:0)

尝试使用此解决方案

([^\\nt\!\&\@\$]+[a-z0-9]+)

在这里测试: https://regex101.com/r/m9e9AH/1