Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

regex - Javascript Regular Expression not matching

Morning All

I have a javascript regular expression that doesn't work correctly and I'm not sure why.

I'm calling the API at https://uptimerobot.com, and getting back a JSON string with details of the monitor statues. This is however wrapped in a function call syntax. Like this:

jsonUptimeRobotApi({MASKED-STATUES-OBJ})

As this call is being made from a generic script I was hoping to test the response to see if it had this type of syntax wrapping then parse it accordingly.

However I can't seem to find a RegEx syntax to match the logic:

  • Start of string
  • An unknown number of characters [a-zA-Z]
  • Open parentheses
  • Open brace
  • An unknown number of any character
  • Close brace
  • Close parentheses
  • End of string

This looks right:

^[a-zA-Z]+({.*})$

And works in regex101: https://regex101.com/r/sE7dM6/1

However it fails in my code and via jsFiddle: https://jsfiddle.net/po49pww3/1/

The "m" was added in regex101 as the actual string is much longer, and failed to match without it, however a number of small tweeks that I've tried havn't resulted in a match in jsFiddle.

Anyone know whats wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Escape all the backslashes one more time because within " delimiters, you must escape the backslash one more time or otherwise it would be treated as an escape sequence.

var regEx = new RegExp("^[a-zA-Z]+\(\{.*\}\)$", "m");

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...