【问题标题】:A regex alternative to split?拆分的正则表达式替代品?
【发布时间】:2011-12-09 20:31:00
【问题描述】:

如何转换下面的字符串

"str 1<tab>str 2<tab>str 3<tab>str 4..........<tab>str n<tab and some whitespace>"

"*str 1*<tab>*str 2*<tab>*str 3*<tab>*str 4*..........<tab>*str n*<tab and some whitespace>"

其中 str 可以是“堆栈 - 溢出”或“超级:用户”,即包含一些空格和特殊字符的单词。

我知道我们可以使用 split 来解决这个问题。有没有办法只使用 =~ s///.. ?

提前致谢!

三位一体

【问题讨论】:

  • &lt;tab&gt; 代表制表还是字面意思&lt;tab&gt;

标签: regex perl


【解决方案1】:
$str =~ s/([^\t]+)/*$1*/g;  # Wrap all non-tab groups with '*'s

要处理“特殊字符”,只需将其添加到不需要的项列表中:

$str =~ s/([^\t:-]+)/*$1*/g;

【讨论】:

  • 那个,或者用“\t”替换所有标签
  • @RichardHuxton:不完全是。它会错过在字符串的开头和结尾添加星号。
猜你喜欢
  • 2010-10-05
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多