我正在尝试从字符串中获取所有单词。它们只能包含字母和数字。但是我完全无法排除可能的\ 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?
谢谢!
答案 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)