[英]Ruby regular expression for this string?
I'm trying to get the first word in this string: Basic (11/17/2011 - 12/17/2011)
我正在尝试获取此字符串中的第一个单词:
Basic (11/17/2011 - 12/17/2011)
So ultimately wanting to get Basic
out of that. 因此,最终希望从中获得
Basic
。
Other example string: Premium (11/22/2011 - 12/22/2011)
其他示例字符串:
Premium (11/22/2011 - 12/22/2011)
The format is always "Single-word followed by parenthesized date range" and I just want the single word. 格式始终为“单字,后跟括号内的日期范围”,我只需要一个字。
Use this: 用这个:
str = "Premium (11/22/2011 - 12/22/2011)"
str.split.first # => "Premium"
The split uses ' '
as default parameter if you don't specify any. 如果未指定,则拆分将使用
' '
作为默认参数。
After that, get the first element with first
在此之后,得到的第一个元素
first
您不需要正则表达式,只需使用
str.split(' ')[0]
我知道您找到了所需的答案,但以防万一将来有人迷失方向,以便从未知长度的大型String
中提取所需的值:
word_you_need = s.slice(/(\b[a-zA-Z]*\b \(\d+\/\d+\/\d+ - \d+\/\d+\/\d+\))/).split[0]
此正则表达式将匹配第一个单词而没有尾随空格
"^\w+ ??"
如果您确实想要一个正则表达式,则可以在使用此正则表达式后获得第一组:
(\w*) .*
"Single-word followed by parenthesized date range" “单字后面加上括号的日期范围”
'word' and 'parenthesized date range' should be better defined 应该更好地定义“单词”和“带括号的日期范围”
as, by your requirement statement, they should be anchors and/or delimeters. 因为根据您的要求声明,它们应该是锚点和/或分界符。
These raw regex's are just a general guess. 这些原始的正则表达式只是一般的猜测。
\w+(?=\s*\([^)]*\))
or 要么
\w+(?=\s*\(\s*\d+(?:/\d+)*\s*-\s*\d+(?:/\d+)*\s*\))
Actually, all you need is: 实际上,您需要做的只是:
s.split[0]
...or... ...要么...
s.split.first
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.