Michael Abraham
Michael Abraham

Reputation: 57

Regex - Match unlimited no. of words of fixed length

I'm fairly new to regex. I'm looking for an expression which will return strings in which the first character is of length 1, followed by an unlimited number of words of length 3 or more.

There should be a space between each word+.

So far I have:

([A-Za-z]{1,1} [A-Za-z+]{3,100})

As it stands this only returns phrases such as:

'I will' and 'A bird'

But I would like it to return phrases like:

'I will always try' and 'A bird flew into the cage'

Any help would be appreciated. I'm using an application called 'Oracle EDQ'.

Upvotes: 2

Views: 4157

Answers (2)

anubhava
anubhava

Reputation: 784998

You can use this regex:

^[A-Za-z](?: [A-Za-z]{3,})+$

RegEx Demo

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You need to apply the limiting quantifier {3,} to the [A-Za-z] group and the * (zero or more repetitions) to the outer group matching a space + the 3+-letter words:

^[A-Za-z]( [A-Za-z]{3,})*$

See regex demo. Note the use of anchors ^ and $ that is very important when you need to match characters at a specific place (here, at the start and end of a word).

Regex matches:

  • ^ - checks the regex engine is at the beginning of a string
  • [A-Za-z] - Exactly 1 letter a to z and A to Z
  • ( [A-Za-z]{3,})* - zero or more sequences of...
    • - a space
    • [A-Za-z]{3,} - 3 or more ASCII letters
  • $ - end of string.

Upvotes: 3

Related Questions