检测开始和结束括号

时间:2018-06-15 09:48:57

标签: ruby regex

来自字符串:

"(book(1:3000))"

我需要排除开始和结束括号并匹配:

"book(1:3000)"

使用正则表达式。

我试过这个正则表达式:

/([^',()]+)|'([^']*)'/

检测除括号外的所有字符和整数。此正则表达式检测到的字符串是:

"book 1:3000"

是否有任何正则表达式无视开始和结束括号,并给出整个字符串?

2 个答案:

答案 0 :(得分:2)

构建明确说明要提取内容的正则表达式:字母数字,后跟左括号,后跟数字,后跟冒号,后跟数字,后跟右括号:

'(book(1:3000))'[/\w+\(\d+:\d+\)/]
#⇒ "book(1:3000)"

答案 1 :(得分:2)

"(book(1:3000))"[/^\(?(.+?\))\)?/, 1]
=> "book(1:3000)"
"book(1:3000)"[/^\(?(.+?\))\)?/, 1]
=> "book(1:3000)"

正则表达式分为多行以便于阅读:

/
 ^      # start of string
  \(?   # character (, possibly (?)
  (     # start capturing
    .+? # any characters forward until..
    \)  # ..a closing bracket
  )     # stop capturing
/x      # end regex with /x modifier (allows splitting to lines)

1。在字符串的开头查找可能的(并忽略它。  2.开始捕捉  3.捕获直到并包括第一个)

但这就是它失败的地方:

"book(1:(10*30))"[/^\(?(.+?\))\)?/, 1]
=> "book(1:(10*30)"

如果你需要这样的东西,你可能需要使用递归正则表达式 在another stackoverflow answer中描述。