【问题标题】:Regex to identify lines in a text with just numbers or single characters正则表达式来识别文本中只有数字或单个字符的行
【发布时间】:2018-11-29 13:38:09
【问题描述】:

伙计们,

我有一个用例,我知道它可以通过 Python 中的传统字符串方法来解决。我正在寻找更多的正则表达式来解决它。

用例:

给定文件中的文本,我想删除所有这样的行 包含任一

  • 只有单个数字(可能在括号中也可能不在括号中),例如 29、[29]、(29)、{29}
  • 只有单个字符(可能在括号中也可能不在括号中),例如 m、[m]、(m)、{m}
  • 只有空行

Python方式(我知道):

  • 如果有空格,则从末尾删除
  • 去掉括号(如果有的话)
  • 对于数字:使用 str.isdigit() 检查字符串是否为数字
  • 对于字符,只需检查此字符串的长度是否等于 1

示例:

hello world...
again hello world...

29 

..
[a]
bye bye...
see you..

预期输出:

hello world...
again hello world...
..
bye bye...
see you..

我想了解如何使用单个正则表达式(如果可能)执行这些步骤。

谢谢!

【问题讨论】:

  • 如果您将其标记为关闭,请注意评论。

标签: python regex string pattern-matching


【解决方案1】:

你可以使用

^[({\[]?(?:\d+|[a-z])?[)}\]]?\s*$[\n\r]

它将被一个空字符串替换,请参阅a demo on regex101.com
开始学习正则表达式时,请尽可能多地打开“详细”模式。


在这种情况下
^         # the start of a line in multiline mode (m flag)
[({\[]?   # a character class ([...]) of (,{ or [ zero or 1 times
(?:       # opening of a non-capturing class
    \d+   # multiple digits
|         # or
    [a-z] # a,b,c,...z
)?        # zero or 1 times
[)}\]]?   # one of ), } or ], zero or 1 times
\s*       # whitespaces, eventually
$         # end of the line
[\n\r]    # newline characters

有关详细信息,请参阅Learning regular expressionsMastering Regular Expressions

【讨论】:

    猜你喜欢
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2018-10-22
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多