Home > Blockchain >  Get text between two signs in a sentence
Get text between two signs in a sentence

Time:12-23

The task is to get text between two signs in a sentence. User input sentence in one line in next one he input signs(for this case it's [ and ]).

Example:

In this sentence [need to get] only [few words].

Output needs to look like:

need to get few words

Can someone have any clue how to do this?

I have some idea like split input so we will access every element of the list and if a first sign is [ and finish with ] we save that word to other list, but there is a problem if the word doesn't end with ]

P.S. user will never input empty string or have a sign inside sign like [word [another] word].

CodePudding user response:

You can use a regex:

import re
text = 'In this sentence [need to get] only [few words] and not [unbalanced'


' '.join(re.findall(r'\[(.*?)\]', text))

Output: 'need to get few words'

Or '(?<=\[).*?(?=\])' as regex using lookarounds

CodePudding user response:

  1. You can use regular expressions like this:
import re

your_string = "In this sentence [need to get] only [few words]"
matches = re.findall(r'\[([^\[\]]*)]', your_string)
print(' '.join(matches))

Regex demo

  1. Solution without regex:
your_string = "In this sentence [need to get] only [few words]"

result_parts = []
current_square_brackets_part = ''
need_to_add_letter_to_current_square_brackets_part = False
for letter in your_string:
    if letter == '[':
        need_to_add_letter_to_current_square_brackets_part = True
    elif letter == ']':
        need_to_add_letter_to_current_square_brackets_part = False
        result_parts.append(current_square_brackets_part)
        current_square_brackets_part = ''
    elif need_to_add_letter_to_current_square_brackets_part:
        current_square_brackets_part  = letter
print(' '.join(result_parts))

CodePudding user response:

Here is a more classical solution using parsing.

It reads the string character by character and keeps it only if a flag is set. The flag is set when meeting a [ and unset on ]

text = 'In this sentence [need to get] only [few words] and not [unbalanced'

add = False
l = []
m = []
for c in text:
    if c == '[':
        add = True
    elif c == ']':
        if add and m:
            l.append(''.join(m))
        add = False
        m = []
    elif add:
        m.append(c)
out = ' '.join(l)
print(out)

Output: need to get few words

  • Related