正则表达式:匹配以任意字符开头的字符串,然后是连字符

2024-10-01 17:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下文本:

BBC-这是短信

如何使用regex测试字符串是否以"* - "开头?

然后删除"* - ",只留下"Here is the text"。(我正在使用python)。

我使用"*",因为它显然不会每次都以"BBC - "开头,它可能是其他子串。

这行吗?

"^.* - "

非常感谢。

回答:

m = re.search(ur'^(.*? [-\xe2\u2014] )?(.*)', text)

这奏效了。谢谢@xanatos!


Tags: the字符串text文本researchhereis
3条回答

使用?运算符:

'^(.+ [-] )?(.+)$'

也许您希望实现它时对空白区域有一点更大的灵活性。。。

一些简单而粗糙的测试脚本(使用php而不是python,抱歉!)以下内容:

<?php
$string  = "BBC - This is the text.";
$pattern = '/^(.+ [-] )?(.+)$/';
preg_match($pattern, $string, $tokens);
var_dump($tokens);
?>

测试剪的输出:

array(3) {
  [0] =>
  string(23) "BBC - This is the text."
  [1] =>
  string(6) "BBC - "
  [2] =>
  string(17) "This is the text."
}

第一个括号与字符串开头的任何文本匹配,该字符串以任何长度的字符开头>;0 whch后跟一个空格字符,然后是文字连字符和另一个空格字符。这种顺序可能存在,也可能不存在。第二个圆括号将字符串的其余部分匹配到最后。

试试这段代码:

str = u"BBC \xe2 abc - Here is the text"
m = re.search(ur'^(.*? [-\xe2] )?(.*)', str, re.UNICODE)

# or equivalent
# m = re.match(ur'(.*? [-\xe2] )?(.*)', str, re.UNICODE)

# You don't really need re.UNICODE, but if you want to use unicode
# characters, it's better you conside à to be a letter :-) , so re.UNICODE

# group(1) contains the part before the hypen
if m.group(1) is not None:
    print m.group(1)

# group(2) contains the part after the hypen or all the string 
# if there is no hypen
print m.group(2)

正则表达式的解释:

^ is the beginning of the string (the match method always use the beginning
  of the string)
(...) creates a capturing group (something that will go in group(...)
(...)? is an optional group
[-\xe2] one character between - and \xe2 (you can put any number of characters
        in the [], like [abc] means a or b or c
.*? [-\xe2] (there is a space after the ]) any character followed by a space, an hypen and a space
      the *? means that the * is "lazy" so it will try to catch only the
      minimum number possible of characters, so ABC - DEF - GHI
      .* - would catch ABC - DEF -, while .* - will catch ABC - 

so

(.* [-\xe2] )? the string could start with any character followed by an hypen
         if yes, put it in group(1), if no group(1) will be None
(.*) and it will be followed by any character. You dont need the 
     $ (that is the end-of the string, opposite of ^) because * will 
     always eat all the characters it can eat (it's an eager operator)

下面是“匹配第一个连字符之前的所有内容和连字符本身”模式:

/^[^-]*-\s*/

全文如下:

^      - starting from the beginning of the string...
[^-]*  - match any number (including zero) of non-hyphens, then...
-      - match hyphen itself, then...
\s*    - match any number (including zero) of whitespace

然后,您可以将模式匹配的字符串替换为空字符串:替换的结果可能是您总体需要的结果。)

相关问题 更多 >

    热门问题