如果一个组不匹配,如何设置NULL?

时间:2016-01-30 00:31:37

标签: javascript jquery regex

我有这个正则表达式:

var match  = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(val);
var before = Number(match[1]) + 1;

现在没有任何匹配,我遇到了这个错误:

  

未捕获的TypeError:无法读取属性' 1'为null

我该如何解决?我想我必须设置NULL而不是match[1]

2 个答案:

答案 0 :(得分:3)

试试这个:

@IBAction func startBubble(sender: AnyObject) { //var bubble = UIView() let screenSize = UIScreen.mainScreen().bounds let screenWidth = screenSize.width let screenHeight = screenSize.height // Animation parameters let duration : NSTimeInterval = 9.0 var delay : NSTimeInterval = 1.0 var minimumDelay : NSTimeInterval = 3.0 let factor : CGFloat = 1.75 let opacity : CGFloat = 0.3 let options: UIViewAnimationOptions = [.CurveEaseIn, .AllowUserInteraction] for bubbleNumber in 1...10 { // Bubble size let bubbleWidth : CGFloat = CGFloat(arc4random_uniform(40) + 130) let bubbleHeight = bubbleWidth // Bubble start position let startPosition : CGFloat = CGFloat(arc4random_uniform(UInt32(screenWidth - bubbleWidth))) // Bubble delay if bubbleNumber > 1 { minimumDelay = minimumDelay + NSTimeInterval(3.0) delay = minimumDelay + (NSTimeInterval(arc4random_uniform(1000)) / 1000) } let bubble = UIImageView(frame: CGRectMake(startPosition, screenHeight, bubbleWidth, bubbleHeight)) // Bubble definition bubble.image = UIImage(named: "bubble.png") bubble.tag = bubbleNumber bubble.userInteractionEnabled = true bubble.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "openBubble:")) self.view.addSubview(bubble) UIView.animateWithDuration(duration, delay: delay, options: options, animations: { bubble.frame = CGRectMake(startPosition, 1, factor*bubbleWidth, factor*bubbleHeight) bubble.alpha = opacity }, completion: { animationFinished in bubble.alpha = 0.1 bubble.removeFromSuperview() }) } } func openBubble(sender:UITapGestureRecognizer){ let tappedBubble = sender.view! print(tappedBubble.tag) }

如果找不到匹配项,则会将var before = ( match === null ) ? 1 : match[1]设置为before,否则应返回正确的匹配项。

答案 1 :(得分:1)

您应首先预先形成一个匹配项以查看是否存在匹配项。

var m = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(val);
var before = m === null ? 0 : +m[1]+1;
/* notice the Array returned by match can be immediately accessed then
   cast to a number with + in front */