regex - Using a positive lookahead to remove the middle of a string -


i'm attempting remove text in middle of string:

renameme_12345_12365_130706t234502.txt 

using following regex:

^[a-za-z]+(?=_[0-9]+_[0-9]+).+$ 

in attempt return:

renameme_130706t234502.txt 

but regex returns entire string without excluding middle:

renameme_12345_12365_130706t234502.txt 

am using positive lookahead incorrectly, or approaching problem incorrectly? can positive lookaheads not used way?

replace regex:

_.*_ 

with

_ 

example sed tool:

kent$  echo renameme_12345_12365_130706t234502.txt|sed 's/_.*_/_/' renameme_130706t234502.txt 

you own tool/programming language.

edit op's comment:

@codingunderduress _.*_ single regex (bre). uses .* greedy character achieve goal.

if don't want substitution, regex match parts need, do:

(^[^_]*|_[^_]*$) 

test grep: (-e means ere)

kent$  echo "renameme_12345_12365_130706t234502.txt"|grep -eo '(^[^_]*|_[^_]*$)'  renameme _130706t234502.txt 

you can of course use look-behind/ahead, if love them. need pcre. , don't see why need use look-around here requirement.


Comments