Dan Winchester
Dan Winchester

Reputation: 344

How to match one or more characters in a string with regex?

Let's say I have a string, for example "abcdef".

I want to match one or more characters in order from the start of the string, for example:

"a"
"abc"
"abcd"

So, it might look a little like this:

/^(abcdef{1,})/

But obviously here the quantifier only applies to the preceding character ("f") whereas I want it to apply to the entire string ("abcdef"). I am hoping there is something I can enclose "abcdef" in to achieve this.

I am using preg_match().

Upvotes: 1

Views: 1676

Answers (3)

user4227915
user4227915

Reputation:

If the order is important, you can use this regex:

\ba(b(c(d(ef?)?)?)?)?

Regex live here.

Upvotes: 3

liusy182
liusy182

Reputation: 205

I think what you need is to enclose abcdef as a set. Try something like

/[abcdef]{1,}/

Upvotes: -1

Termininja
Termininja

Reputation: 7036

Another variant to match exactly "one or more characters from the start of the string" is:

^(abcdef|abcde|abcd|abc|ab|a)

Upvotes: 2

Related Questions