【问题标题】:Using Regex as delimeter to split a string使用正则表达式作为分隔符来分割字符串
【发布时间】:2011-04-12 05:26:14
【问题描述】:

我想将以下字符串拆分为两个子字符串。 "somestring(otherstring)"

我带来了以下正则表达式拆分

"somestring(otherstring)".split(/(.+)\((.+)\)/)

但这不包括以下字符串,它们没有大括号中的子字符串.. “一些字符串”

如何更改正则表达式,即使没有模式“(otherstring)”的子字符串,它仍然会生成第一个子字符串作为输出。

提前非常感谢!

【问题讨论】:

    标签: ruby regex split


    【解决方案1】:
    >> "somestring(otherstring)".split(/[()]/)
    => ["somestring", "otherstring"]
    >> "somestring".split(/[()]/)
    => ["somestring"]
    

    【讨论】:

    • 完美运行,看起来也很漂亮。如果你能告诉我正则表达式正在做什么,那将有很大帮助。谢谢。
    • () 都在方括号内。这称为字符类。这意味着拆分 ()
    【解决方案2】:

    尝试使用类似这样的正则表达式:/([^\(\)]+)(?:\((.+)\))?/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2015-08-22
      • 2014-11-06
      • 1970-01-01
      相关资源
      最近更新 更多