user3162489
user3162489

Reputation: 33

Regular Expression to match a specific string or a digit

I am using java programming language. I want to write a regular expression which would match a specific string(e.g. boy) or a digit(from 5-8) at the start of the string. The successful input shall only be :

  1. boy ....
  2. 7 .... (here 7 can be replaced by 5,6,8)

How to do this?

In all other cases, the return value shall be false.Any solution or suggestion will be appreciated .

Upvotes: 1

Views: 75

Answers (1)

anubhava
anubhava

Reputation: 785156

You can use this regex:

^(boy|[5-8])

Explanation:

^ 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

Upvotes: 2

Related Questions