正则表达式在花括号之间获取字符串 [英] Regex to get string between curly braces

查看:108
本文介绍了正则表达式在花括号之间获取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,尽管尽我所能记住,尽管每年尝试至少一年学习一次正则表达式,但我却经常忘记,因为我很少使用它们.今年,我新年的决定是不再尝试学习正则表达式-因此,今年,为了让我免于眼泪,我将其交给Stack Overflow . (上次圣诞节混音).

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).

我想传入此格式为{getThis}的字符串,然后返回字符串getThis.有人能协助我们坚持我的新年决议吗?

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 \n 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表示以一个字符开始(刚好在第一个{之后),,g.length-1)表示以字符开始直到(但不包括)字符串长度减去一个的字符.之所以有效,是因为该位置从零开始,即g.length-1是最后一个位置.

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 }"

                  这篇关于正则表达式在花括号之间获取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆