-2

Answered by npinti below. The C# answers were not helpful at all in the 'similar question'.

So I have the following regex. I also tried different variations of this, but it will not work unfortunately.

So if I have the below string and would like to extract 23, 22 and 38. But I don't want it to extract the the numbers that are separated with a hyphen and also no negative numbers: -.

string = 'Have to find 23, but not 44-58 and definitely not 88-99 but do find 22 & 38' 

my_regex = re.compile(r'(\d+)|^((?![0-9]+[^-]^[0-9]+).)*$', flags=re.I)
print(my_regex.findall(string))

This basically returns nothing useful.

N90J
  • 57
  • 7

1 Answers1

0

You can try something like so: \b(?<!-)\d+(?!-)\b. This will basically look for numbers which aren't preceded by a - and not followed by a - by using a negative look behind and negative look ahead.

Example here.

Note: The \b is there to ensure that given 12-34, the expression does not match 1 (since it is not followed by a -) and 4 (since it is not preceded by a -).

npinti
  • 51,780
  • 5
  • 72
  • 96
  • Works perfectly thank you! And for those looking at the C# question, the answers there did not work for me so this is not a duplicate. This answer actually works! – N90J Aug 01 '20 at 10:34
  • 1
    @N90J The solution there is working, you just need to replace `.` with `-`: https://ideone.com/sMz6Yo – Wiktor Stribiżew Aug 01 '20 at 18:19