Ryder
Ryder

Reputation: 361

How to make optional assertions in regex?

I have a sample string like this: aibicidieif (of more complicated string but similar format) and I tried a regex like (?<=i).*?(?=i) but it doesn't capture the first and last elements a and f.

I want everything in between the i delimiter but the regex only search for characters that have i before and after it. Is there a way to make (?=i) and (?<=i) optional?

http://regexr.com?30mjf

Upvotes: 2

Views: 211

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 208565

What language are you using? In most languages you are able to split a string using a regex, for example in Python:

>>> re.split(r'i', 'aibicidieifi')
['a', 'b', 'c', 'd', 'e', 'f', '']

Here r'i' could be replaced with a string representing whatever the more complicated regex is.

Alternatively you could do something like this:

(?<=i|^).*?(?=i|$)

By adding anchors with alternation to the lookahead and lookbehind you will now still match characters at the start and end of strings, however some languages don't support variable length lookbehinds so this may not work.

If your language does not support variable length lookbehinds, here is an alternative that should still work:

(?:(?<=i)|^).*?(?=i|$)

Upvotes: 4

joe92
joe92

Reputation: 643

Assuming the input string and the delimiter are as straightforward as you are making them out to be, just do,

$valuesArray = explode('i', $input);

Then access the values from the created array.

Upvotes: 0

Michał Trybus
Michał Trybus

Reputation: 11804

Won't simply [^i]+ do the job?

Upvotes: 0

Related Questions