2

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'] ?

0

2 Answers 2

2

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']
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.