javascript - 从字符串消息中获取子字符串以推入数组
问题描述
所以基本上我想从一条带有“@”或“#”之类的特殊字符的消息中获取用户,并将其推送到 user_lists,而只有用户没有特殊字符。
我知道使用正则表达式进行匹配,但我在将每个匹配项推送到数组时遇到了麻烦。
const user_lists = []
const sample_message = '@user and #user2 has a challenge of time management'
我的想法是使用包含但它只返回布尔值。请帮忙。
有效用户名:没有空格和特殊字符。只需获取所有以 @ 或 # 开头的用户名
解决方案
尝试使用match()
(?<=@|#)\w+
const sample_message = '@user and #user2 has a challenge of time management'
const user_lists = sample_message.match(/(?<=@|#)\w+/g) || []
console.log(user_lists)
推荐阅读
- python - 当我导入任何库(如 Pandas)时,Visual Studio Code 运行速度极慢
- python - 不出错但不创造任何东西
- reactjs - Jest 无法解析 React 应用程序中的项目路径
- mongodb - 如何在mongo集合中的变量中传递列名
- html-table - 试图删除数据表上的单元格边框,但标签“单元格边框”不起作用
- django - django queryset 无法区分使用子查询的结果?
- ruby-on-rails - 向仅 API 的 Rails 应用程序添加会话管理
- listview - Xamarin 侧边菜单弹出刷新
- c++ - Visual Studio 2017 图表设计器工具箱仅在我的 C++ 项目中有评论
- python - 如何使自定义对象中未公开的某些属性?不使用 self.__name