首页 > 解决方案 > matching string using regular expression

问题描述

text = "hellovision hey creator   yoyo  b  creator great  publisher"

I want to extract creator's name and publisher's name from text.

The result will be,

creator = hellovision hey, yoyo

publisher = great

How can I get text using regular expression?

Do I need to use span()..?

This is my code.

def preprocess2(text):

    text_list = test.split(' ')
    lyricist = []
    composer = []
    music_arranger = []
    temp = []
    lyricist.clear()
    composer.clear()
    music_arranger.clear()
    for i in range(0, len(text_list)):
        if text_list[i] == 'creator':
            print(len(text_list))
            for a in range(0, i-1):
                temp.append(text_list[a])
            lyricist.append(''.join(temp))
            temp.clear()
            for b in range(0, i+1):
                print(b)
                text_list.pop(b)
                print(len(text_list))
            break
        elif text_list[i] == 'pulisher':
            for a in range(0, i-1):
                temp.append(text_list[a])
            composer.append(''.join(temp))
            temp.clear()
            for b in range(0, i+1):
            text_list.pop(b)
        break
    i = i +1
return text_list

标签: regexstringmatch

解决方案


If you split your array using regex with a capture group, the value that you split on will also be passed into the output array.

You can then loop through looking for 'creator' or 'publisher' and in each case, pass the previous entry into the proper collection.

const text = "hellovision hey creator   yoyo  b  creator great  publisher"

const splitArr = text.split(/(creator|publisher)/)

const creators = [], publishers = []

let i = -1, len = splitArr.length

while(++i < len){
  if(splitArr[i] == "creator") creators.push(splitArr[i-1].trim())
  else if(splitArr[i] == "publisher") publishers.push(splitArr[i-1].trim())
}

console.log("creators: ", creators)
console.log("publishers: ", publishers)


推荐阅读