Milos Cuculovic
Milos Cuculovic

Reputation: 20223

RegEx and PHP - How to match with a non mandatory parameter

I am using this RegEx:

\s*((\w*\.*\s*)+[.*(\w)]+(?=\d{4}))(\d{4}\s*\,)*

And the goal is to match words with the last one that ends with a dot, follower with 4 digits ending with a comma.

This is a test.2014,

And it works fine. Now, I would like to add the possibility to have a whitespace (\s) between the "test." and "2014,", but the whitespace is not a mandatory parameter, it should be matched if there.

Could you please help me on how to add that to my regex? How can we set not mandatory parameters ?

Thank you.

Upvotes: 0

Views: 953

Answers (4)

Toto
Toto

Reputation: 91385

And the goal is to match words with the last one that ends with a dot, follower with 4 digits ending with a comma

(?:\s*\w+)*\s*\w+\.\d{4},

Now, I would like to add the possibility to have a whitespace (\s) between the "test." and "2014,", but the whitespace is not a mandatory parameter,

(?:\s*\w+)*\s*\w+\.\s*\d{4},

Upvotes: 1

CreationTribe
CreationTribe

Reputation: 572

There are a couple ways you can do this. You can use the question mark, an asterisk, or you can specify the range of viable occurrences as is shown in the table below.

Regular Expressions Quantifiers
*   0 or more
+   1 or more
?   0 or 1
{3} Exactly 3
{3,}    3 or more
{3,5}   3, 4 or 5

\s*((\w*\.*\s*)+[.*(\w)]+(\s+)(?=\d{4}))(\d{4}\s*\,)*
\s*((\w*\.*\s*)+[.*(\w)]+(\s*)(?=\d{4}))(\d{4}\s*\,)*
\s*((\w*\.*\s*)+[.*(\w)]+\s{0,1}(?=\d{4}))(\d{4}\s*\,)*

Upvotes: 1

Victor Bocharsky
Victor Bocharsky

Reputation: 12306

Try this pattern

\s*((\w*\.*\s*)+[.*(\w)]+\s*(?=\d{4}))(\d{4}\s*\,)*

\s* there is a zero or more time space. I added it before date pattern

Or try:

\s*((\w*\.*\s*)+[.*(\w)]+(?=\s*\d{4}))(\s*\d{4}\s*\,)*

Upvotes: 1

Rakesh Advani
Rakesh Advani

Reputation: 45

Try this

/\s*((\w*\.*\s*)+[.*(\w)]+(\s*)(?=\d{4}))(\d{4}\s*\,)*/

Upvotes: 0

Related Questions