Rene
Rene

Reputation: 5

Matching optional String regex

i have to find a solution for my little Problem :-/.

I have a message eg

Status: OK

or

Status: ERR|next Message

is it possible to create a regex for "Status" + optional the Message if exists ?

Thanks a lot

Rene

Upvotes: 0

Views: 1306

Answers (2)

Jon Gauthier
Jon Gauthier

Reputation: 25592

/Status: (\w+)(\|(.+))?/

This will capture the status code (OK, ERR) in the first group, and a message (if present in the string) in the third group.

Upvotes: 0

mikaelb
mikaelb

Reputation: 2148

You can use something like this:

/^Status:\s*([A-Z]+)(?:\|([^$]*))?$/

This matches all the data, and returns OK or ERR as the first element, and only the message as the second element.

Additional information: The (?: notation (before the \|), is a "hidden" grouping. That is, group but don't fetch.

Upvotes: 4

Related Questions