regex - 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
解决方案
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)
推荐阅读
- sql - 查找具有多个不同列值的记录
- reactjs - 如何在 React Material UI 的 AppBar 组件中设置容器?
- php - 如何计算等级然后传递给刀片模板
- typescript - 类型“FormArray”不可分配给类型“any[]”。“FormArray”类型中缺少属性“includes”。在 angular6 打字稿中
- sql - 创建表的SQL命令
- twig - 为什么 slim 需要完整的目录路径来加载外部资产(js/css)文件
- d3.js - 在 dc.js 图表中放大后,D3-tip 工具提示卡住了
- wordpress - 如何在谷歌搜索中从子域 wordpress TITLE 中隐藏主域 TITLE 名称
- php - get_terms WP_Error 对象([错误] => 数组([invalid_taxonomy] => 数组([0] => 无效分类。))[error_data] => 数组())
- android - android谷歌地图标记空指针错误