使用正则表达式查找单词 [英] Using regexp to find a word

查看:117
本文介绍了使用正则表达式查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条推文,我需要查找主题标签说的话.我如何使用正则表达式将以'#'开头和以''结尾的所有内容隔离并将其保存到变量中?我正在使用MatLab.

I have a tweet and I need to find what the hashtags say. How can I isolate and save to a variable everything that starts with a '#' and ends with a ' ' using regexp? I'm using MatLab.

推荐答案

当您不熟悉正则表达式时,使用它们可能会很有挑战性.

Regular expressions can be challenging to use when you're not familiar with them.

这是查找主题标签的一种方法:

Here's one way to find a hashtag:

tweet = 'it is fun to post on #stackoverflow, really';
regexp(tweet,'#(\w+)','tokens','once')
ans = 
    'stackoverflow'

#(\ w +)的作用是什么?我们使用 \ w 查找单词"字符(无空格,标点符号),并指定我们至少要使用 + 其中之一.这个词必须以#开头.我们使用括号指示要返回的部分,并使用选项 tokens 使其返回匹配项(我不在乎主题标签在推文中的位置).我将选项设置为一次,以便 regexp 仅查找一个标签.如果您希望在推文中包含多个主题标签,请不要这样做,但是请注意,输出将是字符串的单元格数组.

What does #(\w+) do? We look "word"-characters (no spaces, no punctuation) with \w, and specify that we want at least one of them +. The word has to start with a #. We use the parentheses to indicate which part we want to be returned, and the option tokens so that it returns the match (I don't care where the hashtag is in the tweet). I set the option once so that regexp only looks for one hashtag; don't do that if you expect multiple hashtags in your tweet, though note that the output will be a cell array of strings.

这篇关于使用正则表达式查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆