mrqwerty91
mrqwerty91

Reputation: 170

Try to split a string with particular regex expression

i'm trying to split a string using 2 separator and regex. My string is for example

"test 10 20 middle 30 - 40 mm".

and i would like to split in ["test 10", "20 middle 30", "40 mm"]. So, splittin dropping ' - ' and the space between 2 digits. I tried to do

result = re.split(r'[\d+] [\d+]', s)
> ['test 1', '0 middle 30 - 40 mm']

result2 = re.split(r' - |{\d+} {\d+}', s)
> ['test 10 20 middle 30', '40 mm']

Is there any reg expression to split in ['test 10', '20 middle 30', '40 mm'] ?

Upvotes: 2

Views: 52

Answers (2)

wwnde
wwnde

Reputation: 26686

Data

k="test 10 20 middle 30 - 40 mm"

Please Try

result2 = re.split(r"(^[a-z]+\s\d+|\^d+\s[a-z]+|\d+)$",k)
result2

**^[a-z]**-match lower case alphabets at the start of the string and greedily to the left + followed by:

 **`\s`** white space characters
 **`\d`** digits greedily matched to the left

| or match start of string with digits \d+ also matched greedily to the left and followed by:

  `**\s**` white space characters
   **`a-z`** lower case alphabets greedily matched to the left

| or match digits greedily to the left \d+ end the string $

Output enter image description here

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may use

(?<=\d)\s+(?:-\s+)?(?=\d)

See the regex demo.

Details

  • (?<=\d) - a digit must appear immediately on the left
  • \s+ - 1+ whitespaces
  • (?:-\s+)? - an optional sequence of a - followed with 1+ whitespaces
  • (?=\d) - a digit must appear immediately on the right.

See the Python demo:

import re
text = "test 10 20 middle 30 - 40 mm"
print( re.split(r'(?<=\d)\s+(?:-\s+)?(?=\d)', text) )
# => ['test 10', '20 middle 30', '40 mm']

Upvotes: 2

Related Questions