Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.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
正则表达式匹配字符串中包含+;和-使用re.findall()Python_Python_Regex_Non Alphanumeric - Fatal编程技术网

正则表达式匹配字符串中包含+;和-使用re.findall()Python

正则表达式匹配字符串中包含+;和-使用re.findall()Python,python,regex,non-alphanumeric,Python,Regex,Non Alphanumeric,myreg=r“\babcb\” 到目前为止,一切都按预期进行,但如果我将我的注册号和注册号更改为 myreg = r"\b\+abcb\" mystr = "sdf +abc" print(re.findall(myreg,mystr)) = [] but i would like to get [+abc] 我已经注意到,使用下面的作品正如预期的那样 myreg = "^\\+abc$" mystr = "+abc" mystr1 = "-+abc" 我的

myreg=r“\babcb\”

到目前为止,一切都按预期进行,但如果我将我的注册号和注册号更改为

myreg = r"\b\+abcb\"

mystr = "sdf +abc"

print(re.findall(myreg,mystr)) = [] but i would like to get [+abc]
我已经注意到,使用下面的作品正如预期的那样

   myreg = "^\\+abc$"

   mystr = "+abc"   

   mystr1 = "-+abc"
我的问题是:是否可以在不拆分字符串的情况下获得与上述相同的结果

致以最良好的祝愿


加布里埃尔有两个问题

  • +abc
    中的
    +
    之前,没有单词边界,因此
    \b
    无法匹配
  • 您的regex
    \b\+abcb\
    尝试在
    abc
    之后匹配文本
    b
    字符(打字)
  • 单词边界

    单词边界在单词字符(字母、数字和下划线)和非单词字符(或行首或行尾)之间的某个位置匹配。例如,
    +
    a

    解决方案:创建自己的边界

    如果您希望匹配
    +abc
    ,但仅当它前面没有单词字符时(例如,您不希望它在
    def+abc
    中),那么您可以使用lookback创建自己的边界:

    (?<!\w)\+abc
    
    (?
    
    这表示“匹配
    +abc
    ,如果前面没有单词字符(字母、数字、下划线)”。

    您的问题如下:

    • \b
      定义为
      \w
      \w
      字符之间的边界 (反之亦然)
    • \w
      包含字符集
      [a-zA-Z0-9\
    • \W
      包含字符集
      [^a-zA-Z0-9\
      ,表示除
      [a-zA-Z0-9\]
      之外的所有字符
    '+'
    不包含在
    \w
    中,因此您将无法匹配空格和
    '+'
    之间的边界

    要获得所需内容,应从模式中删除第一个
    \b

    import re
    
    string = "sdf +abc"
    pattern = r"\+abc\b"
    matches = re.findall(pattern, string)
    
    print matches
    ['+abc']
    
    import re
    
    string = "sdf +abc"
    pattern = r"\+abc\b"
    matches = re.findall(pattern, string)
    
    print matches
    ['+abc']