2

I have this bash statement with perl regex:

echo $1 | perl -pe 's|(?:://).+?(?:/)|b|'

prints this:

httpbTesting/JS/displayName.js

from this:

http://php2-mindaugasb.c9.io/Testing/JS/displayName.js

I was expecting:

http://b/Testing/JS/displayName.js

Maybe I don't understand something about the non-capturing groups? I thought they are supposed to match, but not capture (like a positive lookahead and look behind combined). Am I mistaken?

1
  • 2
    Re "please also advise on how non-capturing groups work", Example 1) /ab{2}/ matchs strings containing abb, while /(?:ab){2}/ matches strings containing abab. Example 2) /ab|c/ matches strings containing ab and strings containing c, while /a(?:b|c)/ matches strings containing ab and strings containing ac
    – ikegami
    Jan 9, 2015 at 18:26

1 Answer 1

5

You should use:

perl -pe 's|(//).+?(/)|$1b$2|'

Non capturing group doesn't mean that input text won't be consumed. Non-capturing parentheses group the regex so you can apply regex operators, but do not capture anything.

Or use lookarounds and avoid capturing groups:

echo "$1" | perl -pe 's|(?<=://).+?(?=/)|b|'
http://b/Testing/JS/displayName.js
8
  • "Non capturing group doesn't mean that input text won't be consumed." please also advise on how they work - would appreciate it Jan 9, 2015 at 17:50
  • 1
    Added more explanation. You can also check: regular-expressions.info/brackets.html
    – anubhava
    Jan 9, 2015 at 17:53
  • 2
    or s|://\K.+?(?=/)|b| - \K (not available in really old perls) sets where the consumption starts
    – ysth
    Jan 9, 2015 at 17:55
  • 2
    Difference is that in (ab){2} regex you have captured group back-reference available as $1 but in (ab){2} you cannot use $1
    – anubhava
    Jan 9, 2015 at 18:16
  • 1
    Sorry I meant (?:ab){2} 2nd time in above comment. To answer your question no non-capturing group doesn't discard the matches. It just doesn't keep it available in back-reference $1, $2, $3 etc.
    – anubhava
    Jan 10, 2015 at 3:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.