正则表达式获取大括号之间的字符串 [英] Regex to get string between curly braces
问题描述
不幸的是,尽管在我记得的很多年里,我每年至少尝试学习一次正则表达式,但我总是忘记,因为我很少使用它们.今年我的新年决心是不再尝试学习正则表达式 - 所以今年为了让我免于流泪,我将它交给 Stack Overflow.(去年圣诞节混音).
我想以这种格式传入一个字符串{getThis}
,然后返回字符串getThis
.任何人都可以帮助我坚持我的新年决心吗?
Stack Overflow 相关问题:
- 如何变成常规引号(即 ', ")转换成 LaTeX/TeX 引号(即`', ``'')
- 正则表达式: 提取字符串中两个标签之间的子字符串
- 正则表达式替换字符串中的所有 ,但没有 [code] [/code] 标签内的那些
如果你的字符串总是采用那种格式,那么正则表达式就显得有些过分了:
<预><代码>>>>var g='{getThis}';>>>g.substring(1,g.length-1)得到这个"substring(1
表示开始一个字符 (刚好经过第一个 {
) 和 ,g.length-1)
表示取字符直到(但不包括)字符串长度减一处的字符.这是有效的,因为位置是从零开始的,即 g.length-1
是最后一个位置.
对于原始海报以外的读者:如果必须是一个正则表达式,请使用 /{([^}]*)}/
如果你想允许空字符串,或者 /{([^}]+)}/
如果您只想在大括号之间至少有一个字符时匹配.细分:
/
:开始正则表达式模式{
:文字花括号(
:开始捕获[
:开始定义一类要捕获的字符^}
:除了}
之外的任何东西"
]
:好的,这就是我们的整个类定义*
:匹配我们刚刚定义的那个类的任意数量的字符
)
:完成捕获
}
:文字花括号必须紧跟我们捕获的内容
/
:结束正则表达式
Unfortunately, despite having tried to learn regex at least one time a year for as many years as I can remember, I always forget as I use them so infrequently. This year my new year's resolution is to not try and learn regex again - So this year to save me from tears I'll give it to Stack Overflow. (Last Christmas remix).
I want to pass in a string in this format {getThis}
, and be returned the string getThis
. Could anyone be of assistance in helping to stick to my new year's resolution?
Related questions on Stack Overflow:
- How can one turn regular quotes (i.e. ', ") into LaTeX/TeX quotes (i.e. `', ``'')
- Regex: To pull out a sub-string between two tags in a string
- Regex to replace all in a String, but no those inside [code] [/code] tag
If your string will always be of that format, a regex is overkill:
>>> var g='{getThis}';
>>> g.substring(1,g.length-1)
"getThis"
substring(1
means to start one character in (just past the first {
) and ,g.length-1)
means to take characters until (but not including) the character at the string length minus one. This works because the position is zero-based, i.e. g.length-1
is the last position.
For readers other than the original poster: If it has to be a regex, use /{([^}]*)}/
if you want to allow empty strings, or /{([^}]+)}/
if you want to only match when there is at least one character between the curly braces. Breakdown:
/
: start the regex pattern{
: a literal curly brace(
: start capturing[
: start defining a class of characters to capture^}
: "anything other than}
"
]
: OK, that's our whole class definition*
: any number of characters matching that class we just defined
)
: done capturing
}
: a literal curly brace must immediately follow what we captured
/
: end the regex pattern
这篇关于正则表达式获取大括号之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!