我想使用java正则表达式查找所有以“#"开头的单词并以空格或“."结尾 [英] I want to find all words using java regex, that starts with "#" and ends with space or "."

查看:390
本文介绍了我想使用java正则表达式查找所有以“#"开头的单词并以空格或“."结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例字符串

hi #myname, you  got #amount

我想使用 java regx 查找所有单词,以 # 开头并以空格或 结尾.示例 #myname,#amount

I want to find all words using java regx, that starts with # and ends with space or . example #myname,#amount

我尝试了以下正则表达式,但不起作用.

I tried the following Regex, but it doesn't work.

String regx = "^#(\\s+)";

推荐答案

这个应该是这样的:

#(\w+)(?:[, .]|$)

  • ## 字面匹配
  • \w 是一个至少包含一个字母的单词
  • (?:) 是非捕获组
  • [, .]|$ 是包括行尾的结束字符集 $
    • # matches # literally
    • \w is a word with at least one letter
    • (?:) is non-capturing group
    • [, .]|$ is set of ending characters including the end of line $
    • 有关详细信息,请查看 Regex101.

      For more information check out Regex101.

      在 Java 中不要忘记用双 \\ 转义:

      In Java don't forget to escape with double \\:

      String str = "hi #myname, you  got #amount";
      Matcher m = Pattern.compile("#(\\w+)(?:[, .]|$)").matcher(str);
      while (m.find()) {
         ...
      }
      

      这篇关于我想使用java正则表达式查找所有以“#"开头的单词并以空格或“."结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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