Steve
Steve

Reputation: 229

How do I make a certain portion of a regular expression optional?

How do I make certain portion of a regular expression optional? For example:

\d* [\\s\\w*?]

...where the expression inside the brackets is optional.

Upvotes: 0

Views: 133

Answers (4)

Myles
Myles

Reputation: 21510

I don't think that's quite the regular expression you want. [\s\w*?] says "match one character that is a space, a word, a star, or a question mark". I think you ultimately what you want is (\s\w)*? which says "match 0 or more of a space followed by a word and don't be greedy about it.

Though you could be looking for (\s|\w)*? which says "match a word or a space 0 or more times and don't be greedy about it."

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993075

Add ? after the ]. The ? means zero or one of the preceding element.

Upvotes: 0

AdamH
AdamH

Reputation: 2201

You can make a bracketed group optional, so (abc)? would work as expected. \d*(\s\w*?)? I think would do what you're describing

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190945

Just add a * after the ]. * means 0 or more.

Upvotes: 0

Related Questions