简体   繁体   中英

Matching “{CHARACTERS}” using Javascript RegExp

I'm really struggling with the Javascript version of Regular Expression matching, despite knowing how to do it in other languages like C# and PHP.

I wish to match {ANYCHARACTERS} .

It must have:

  • a { at the start
  • a } at the end
  • 1 or more characters between (any characters, symbols etc.)

So far I have the following:

<script type="text/javascript">

// The string that I want to perform a match on
var str = "{ASTRINGINHERE£$%^&*éáó}";

// Mt Matching expression
var patt1 = ^/{(.*){1,*}/}$/i;

// Write the matched result
document.write(str.match(patt1));

</script>

As written, your current pattern should result in a javascript syntax error. Here are the problems I see:

  • You have your ^ character outside the actual regular expression.
  • You have two regular expression ending characters ( / ).
  • See @kopischke's answer on why I removed the {1,} portion.

This should resolve your issues:

/^{(.+)}$/i

The string start / string end codes belong inside the regex. Also, your repetition code is unnecessarily complex. Finally, there is no need to indicate case independence when you match any character. This should do:

patt1 = /^{.+}$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM