Skip to main content
 首页 » 编程设计

python之正则表达式/Python : Find everything before one symbol, 如果它在另一个符号之后

2024年08月16日47zdz8207

如果有一个长破折号 ("―"),则返回完整的字符串,如果为真,则返回第一个逗号 (",") 之前的所有内容。我如何使用 Python 和 Regex 来做到这一点?

from bs4 import BeautifulSoup 
import requests 
import json 
import pandas as pd 
 
request = requests.get('https://www.goodreads.com/quotes/tag/fun?page=1') 
soup = BeautifulSoup(request.text, 'lxml') 
# for loop 
s = soup.find_all("div", class_="quoteText")[0].text 
s = " ".join(s.split())  
s[:s.index(",")] 
s 

原始输出:

“That does it," said Jace. "I\'m going to get you a dictionary for Christmas this year.""Why?" Isabelle said."So you can look up \'fun.\' I\'m not sure you know what it means.” ― Cassandra Clare, City of Ashes //<![CDATA[ function submitShelfLink(unique_id, book_id, shelf_id, shelf_name, submit_form, exclusive) { var checkbox_id = \'shelf_name_\' + unique_id + \'_\' + shelf_id; var element = document.getElementById(checkbox_id) var checked = element.checked if (checked && exclusive) { // can\'t uncheck a radio by clicking it! return } if(document.getElementById("savingMessage")){ Element.show(\'savingMessage\') } var element_id = \'shelfInDropdownName_\' + unique_id + \'_\' + shelf_id; Element.upda 

期望的输出:

“That does it," said Jace. "I\'m going to get you a dictionary for Christmas this year.""Why?" Isabelle said."So you can look up \'fun.\' I\'m not sure you know what it means.” ― Cassandra Clare 

请您参考如下方法:

这是一种解决方案:

import re 
 
s = 'adflakjd, fkljlkjdf ― Cassandra Clare, City of Ash, adflak' 
 
x = re.findall('.*―.*?(?=,)', s) 
 
 
print x 
 
['adflakjd, fkljlkjdf ― Cassandra Clare']