Search code examples
phpregexregex-groupregexp-replace

Without the g flag RegEX return wired output


Regex

m/(b?)-/ [here no g flag]

Sample input

a-b-

Current matching

-

Desired matching

b-

My doubt is about why without a global flag b- is not matched

(b?) is optionally matching literal b

"-" is matched literal -

finally, I get only - this one?

$ echo "a-b-" | sed 's/\(b\?\)-/x\u\1/g'
axxB
$ 
$ echo "a-b-" | sed 's/\(b\?\)-/x\u\1/'
axb-

In the last sed replacement, the first occurrence of - is replaced by x what about the b-


Solution

  • Without the global flag regex will return first match only. Since your regex is b?- with optional b therefore it returns first - from input a-b-.

    If you still want to match b- even though - appears first then you can use this regex with a negative lookahead:

    b?-(?!.*b-)
    

    This will match optional b followed by a - only if there is no b- on right hand side since we are using a negative lookahead.

    RegEx Demo 1

    If there is no b- then it will match first -.

    RexEx Demo 2