正则表达式匹配特定字符串或数字

时间:2014-01-12 14:35:25

标签: java regex

我使用的是java编程语言。 我想写一个正则表达式,它匹配字符串开头的specific string(e.g. boy)或数字(from 5-8)。 成功输入只能是:

  1. 男孩....
  2. 7 ....(此处7可以替换为5,6,8)
  3. 怎么做?

    在所有其他情况下,返回值应为false。任何解决方案或建议都将受到赞赏。

1 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式:

^(boy|[5-8])

<强>解释

^ assert position at start of the string
1st Capturing group (boy|[5-8])
1st Alternative: boy
boy matches the characters boy literally (case sensitive)
2nd Alternative: [5-8]
[5-8] match a single character present in the list below
5-8 a single character in the range between 5 and 8