A. Learner
A. Learner

Reputation: 3

Regex matching zero or none and Or

How do I match a sequence of optional characters or a different character?

For example:

I started with matching the letters "KQkq"

these are in sequence but optional, so "K?Q?k?q?"

however the input is either one of those four letters or "-", so I tried "(K?Q?k?q?|-)"

this works for the letters, but won't match the "-"

If the letters weren't optional I'd use "(KQkq|-)", which works fine.

I've tried a number of different things, like putting the letters in a group "((K?Q?k?q?)|-)" but I can't quite find a way to express what I need.

*** Note: As I stated in the question: I'm matching the letters "KQkq" "in sequence but optional". Sequence means they come one after the other so "KQkq" is valid, "KkQq" is not valid, nor is "kqKQ" or "kkkk" or anything else that doesn't match the sequence KQkq. Optional means that a character may or may not exist. So "KQkq" is valid, as is "K" or "Kk" or "Qkq". Character classes, for those that don't know, will match any of the characters in the class with no sense of sequence. So [KQkq]{1,4} would indeed match "KQkq" and "Qkq" however it would also match "KKKK", "qkQK", "qqqq" none of which are valid.

Upvotes: 0

Views: 655

Answers (5)

Toto
Toto

Reputation: 91508

Your regex is working fine, in order to capture the dash you just need to anchor the regex:

^(K?Q?k?q?|-)$

Without anchor, the first part K?Q?k?q? matches anything, included empty string and -.

Upvotes: 1

vks
vks

Reputation: 67988

^(?:(?:K?Q?k?q?)|-)$

Try this.See demo.

https://regex101.com/r/gQ3kS4/2

Upvotes: 1

Luke
Luke

Reputation: 7220

I think this will do what you need: (K?Q?k?q?|-)

Upvotes: 0

Ian Hazzard
Ian Hazzard

Reputation: 7771

Try using square brackets, like this: /[KQkq]|-/. Anything inside square brackets is optional. It literally means match anything between the brackets.

Upvotes: 0

dhershman
dhershman

Reputation: 341

Have you tried doing ([KQkq]|-) or even ([KQkq]|[-])

Example: Regex Example

Upvotes: 0

Related Questions