Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 遇到特定单词时拆分字符串_Python_Regex_String_String Matching - Fatal编程技术网

Python 遇到特定单词时拆分字符串

Python 遇到特定单词时拆分字符串,python,regex,string,string-matching,Python,Regex,String,String Matching,作为一个整体,我对python和编程相当陌生。只是学习我的基础知识。比方说,我有一根这样的绳子 s = "DEALER:'S up, Bubbless? BUBBLES: Hey. DEALER: Well, there you go. JUNKIE: Well, what you got?DEALER: I got some starters."; 我希望字符串在遇到以大写和冒号(:)结尾的单词时结束。然后创建一个新字符串来存储另一个字符串。对于上面的字符串,我将获得 s1 = "DEAL

作为一个整体,我对python和编程相当陌生。只是学习我的基础知识。比方说,我有一根这样的绳子

s = "DEALER:'S up, Bubbless? BUBBLES: Hey. DEALER: Well, there you go. JUNKIE: Well, what you got?DEALER: I got some starters.";
我希望字符串在遇到以大写和冒号(:)结尾的单词时结束。然后创建一个新字符串来存储另一个字符串。对于上面的字符串,我将获得

 s1 = "DEALER:'S up, Bubbless?"
    s2 = "BUBBLES: Hey."
    s3 = "DEALER: Well, there you go."
这是我的正则表达式代码

mystring = """
DEALER: 'S up, Bubbless?
BUBBLES: Hey.
DEALER: Well, there you go.
JUNKIE: Well, what you got?
DEALER: I got some starters. """

#[A-Z]+:.*?(?=[A-Z]+:|$)

#p = re.compile('([A-Z]*):')
p = re.compile('[A-Z]+:.*?(?=[A-Z]+:|$)')
s = set(p.findall(mystring))

我如何循环通过它来获得每个字符串?它只会得到第一个字符串(即发牌商:“S up,无泡?”并停止。对不起,如果我听起来有点不知所措。对编程来说有点陌生。边练习边学习

由于它是一个多行字符串,您需要使用
re.DOTALL
选项,如下所示

p = re.compile('[A-Z]+:.*?(?=[A-Z]+:|$)', re.DOTALL)
输出

set(["DEALER: 'S up, Bubbless?\n",
     'JUNKIE: Well, what you got?\n',
     'DEALER: Well, there you go.\n',
     'DEALER: I got some starters. ',
     'BUBBLES: Hey.\n'])
引用

使“.”特殊字符完全匹配任何字符,包括 新线;如果没有此标志,“.”将匹配除换行以外的任何内容

因此,如果没有该选项,
*?
\n
不匹配。这就是为什么没有其他字符串匹配的原因