# How to Do This LookBehind in Regex?

Data: `1.000000000000002`, `0.999999999999999`
Expected output: `1.0..02`, `0.9..9` where you can replace `..` with any other shorthand for cut
Pseudocode in Matlab

``````float_thing=1.0000000000000002; % 0.999999999999999
str=num2str(float_thing,17);
regexprep(str, '[09]{3,}' , 'SOME_lookBehind_thing_here for 0..0/9..9')
``````
1. you have a float `float_thing`
2. you convert/cast it to string by `num2str` with 17 digit precision
3. you use regular-expression by `regexprep` where you replace the string `str` with the match `[09]{3,}` i.e. all characters of zeros and nines whose count is at least three, with the replacement `0..0` and `9..9`, respectively
• the last part should be possible where you should use lookBehind possibly in the last part

Matlab version based on Stephane's answer and docs

``````% http://se.mathworks.com/help/matlab/matlab_prog/tokens-in-regular-expressions.html
p=1.0000000000000002; str=num2str(p,17); regexprep(str, '([09])\1{3,}' , '\$1..\$1')
% 1.0..02

p=0.9999999999999999; str=num2str(p,17); regexprep(str, '([09])\1{3,}' , '\$1..\$1')
% 0.9..989
``````

System: Linux Ubuntu 16.04
Languages: Perl, Matlab, Unix, Bash, Python, ...

• Do you really want the `..` characters in the output? – roaima Aug 8 '16 at 14:45

``````\$ echo 1.000000000000002, 0.999999999999999, 999.000999000999|
sed 's/\([09]\)\1\{2,\}/\1..\1/g'
1.0..02, 0.9..9, 9..9.0..09..90..09..9
``````

That is a `[09]` followed by itself (`\1` being a backreference to the `[09]` captured in the capturing group `\([09]\)`) repeated 2 or more times. Note that it's different from `[0-9]\{3,\}` which would match `0000` but also `0909`.

Not all regular expression syntaxes support back-references. Standard Basic Regular Expressions as used by `sed` do, Standard Extended Regular Expressions (like in `egrep`) don't though some implementations of ERE support it as an extension. That's the case of GNU `sed` with the `-r`/`-E` option (another non-standard extension) with which you could use `sed -E 's/([09])\1{2,}/\1..\1/g'` here.

Perl and compatible regular expressions do, and it looks like MATLAB regular expressions support them too, and even support named backreferences like in `perl`.