-2

Hello straight to the point: I have this regex:

Regex

You can see regex (?:-|role:)??\binfo-ansible[\s|,] I'm trying to match all strings in this case "info-ansible" with rules:

  • It has to start by "- " or "role: " (example: role: info-ansible)
  • It has to end either by white-space or ","

Those rules are already implemented into regex

In the very first match you can see it matched info-ansible, I dont want "," to be included in the match.

Seems to be like very simple problem but i spent so much time on it already.

The is link to online regex tool with those texts already in: https://regex101.com/r/Xixz3O/3

0stone0
  • 34,288
  • 4
  • 39
  • 64
Martin Tomko
  • 155
  • 1
  • 1
  • 13
  • 2
    `(?:-|role:)?\binfo-ansible(?=[\s,])`? See https://regex101.com/r/9oJCYu/1 – Wiktor Stribiżew Sep 09 '20 at 11:36
  • @WiktorStribizew Comments should be for improving the question, not answering it. With a brief explanation of what you're suggesting, that would make a good answer. – IMSoP Sep 09 '20 at 11:40
  • Depending on the context you might also use a word-boundary `\b` or just nothing at all, if there are no other elements of which `info-ansible` is a prefix. – tobias_k Sep 09 '20 at 11:41

1 Answers1

0

Use a positive lookahead on the whitespace|comma capture;

So instead of [\s|,] use (?=[\s,])

(?:-|role:)??\binfo-ansible(?=[\s,])

Try it online!


Simplified (Thx @Wiktor Stribiżew);

(?:-|role:)?\binfo-ansible(?=[\s,])
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Note the lazy `??` quantifier in `(?:-|role:)??` will work the same way as with a greedy `?`, as the string is read from left to right, and if there is `-` or `role:`, they will get consumed anyway. – Wiktor Stribiżew Sep 09 '20 at 11:41
  • Glad it worked, please note (as @WiktorStribiżew said) the first `??` could be avoided! – 0stone0 Sep 09 '20 at 11:48