【问题标题】:special character at the begin who match with the end from every word [only regex]开头的特殊字符与每个单词的结尾匹配[仅正则表达式]
【发布时间】:2010-08-31 16:33:29
【问题描述】:

什么是使用正则表达式的最佳解决方案,从每个单词的开头和结尾删除特殊字符。

"as-df-- as-df- as-df (as-df) 'as-df' asdf-asdf) (asd-f asdf' asd-f' -asdf- %asdf%s asdf& $asdf $ +asdf+ asdf++ asdf''"

输出应该是:

"as-df-- as-df- as-df (as-df) as-df asdf-asdf) (asd-f asdf' asd-f' asdf %asdf%s asdf& asdf asdf asdf++ asdf'' "

如果开头的特殊字符与结尾匹配,则将其删除

我正在学习正则表达式。 [仅正则表达式]

【问题讨论】:

  • 您的示例输入或输出中似乎有错误......在第一行的末尾,+asdf+ 变为asdf++ ??另外,“特殊字符”的确切集合是什么?例如。除空格以外的所有非字母数字字符?什么构成单词边界?应该去除多个匹配的特殊字符,还是只去除一对?
  • 另外,正则表达式语言有很多方言,所以如果你想得到一个适合你的答案,指定方言会很有帮助。

标签: python regex


【解决方案1】:
import re
a = ("as-df-- as-df- as-df (as-df) 'as-df' asdf-asdf) (asd-f"
     "asdf' asd-f' -asdf- %asdf%s asdf& $asdf$ +asdf+ asdf++ asdf''")
b = re.sub(r"((?<=\s)|\A)(?P<chr>[-()+%&'$])([^\s]*)(?P=chr)((?=\s)|\Z)",r"\3",a)
print b

给予:

as-df-- as-df- as-df (as-df) as-df asdf-asdf) (asd-f
asdf' asd-f' asdf %asdf%s asdf& asdf asdf asdf++ asdf''

让不同的字符工作是个骗局()[]{}

【讨论】:

  • 这不符合 OP 的要求,即不能更改 asdf-asdf)
  • @M42 有点固定,有一个警告
  • () 是不同的字符。
【解决方案2】:

对于 Perl,/\b([^\s\w])\w+\1\b/g 怎么样?请注意,像 \b 这样的东西并不适用于所有正则表达式语言。

糟糕,正如@Nick 指出的那样,这不适用于不同的对,例如 () [] 等。

你可以这样做:

 s/\b([^\s\w([\]){}])\w+\1\b/\2/g
 s/\b\((\w+)\)\b/\1/g
 s/\b\[(\w+)\]\b/\1/g
 s/\b\{(\w+)\}\b/\1/g

(未经测试)

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    相关资源
    最近更新 更多