简体   繁体   English

如何摆脱正则表达式结果中的“未定义”?

[英]How to get rid of “undefined” in regexp result?

I do not understand why undefined appears in result. 我不明白为什么undefined出现在结果中。 I use a question mark (\\d+)? 我用问号(\\d+)? , it matches the previous element zero or one time : ,它匹配前一个元素零次或一次

// I want to match two cases with one regexp:
//   "GBP 5 per hour" and "GBP 5 per 10 hours"
//
"GBP 5 per hour".match(/([a-z]{3}) (\d+(?:\.\d+)?) per\s?(\d+)?\s?(hours?|days?|minutes?)/im)
["GBP 5 per hour", "GBP", "5", undefined, "hour"]  // actual result
["GBP 5 per hour", "GBP", "5", "hour"]  // the result I'd like to get

How to get rid of that undefined ? 如何摆脱那种undefined

The result will be the data (text) that is matched, if you are saying you want to match zero or one, and it matches zero then there is no data to return, and undefined is the result of that. 结果将是匹配的数据(文本),如果您要匹配零或一,并且它匹配零则则没有要返回的数据,并且未定义是结果。

I would speculate that the design reason as to why the match is preserved is because it keeps the indexes consistent, so you can still access them as you would expect to. 我推测保留匹配原因的设计原因是因为它使索引保持一致,因此您仍然可以按照预期访问它们。 This way it enables you to effective test "was anything matched" by checking for undefined . 通过这种方式,它可以通过检查undefined来有效地测试“是否匹配”。

If you want to remove it from the array then you could use the filter function, for example: 如果要从阵列中删除它,则可以使用filter功能,例如:

arr = arr.filter(function(e){return e});

( Which I stole from here ) 我从这里偷走了

try 尝试

var x = ["GBP 5 per hour", "GBP", "5", undefined, "hour"];
var y = x.filter(Boolean);

as in Javascript any non-proper value is false that should help. 在Javascript中,任何非正确的值都是错误的,应该有所帮助。 Found it a few months ago written by Elad here 几个月前由Elad 在这里发现它

No simpler than 不比简单

"GBP 5 per hour"
    .match(/([a-z]{3}) (\d+(?:\.\d+)?) per\s?(\d+)?\s?(hours?|days?|minutes?)/im)
    .filter(function(i){return typeof i != 'undefined'})

Since match will return an array, you can filter its elements with the filter method. 由于match将返回一个数组,您可以使用filter方法过滤其元素。 The filter method can accept a callback (closure, function name as string, ...). filter方法可以接受回调(闭包,函数名称为string,...)。 Array elements are iterated and every element is passed to the callback function and is only accepted if the callback return value is equivalent to Boolean True 迭代数组元素,每个元素都传递给回调函数, 只有当回调返回值等于Boolean True 时才接受

Hope it helps 希望能帮助到你

The problematic part of your RegEx is: 您的RegEx中有问题的部分是:

per\s?(\d+)?\s?

Three possible solutions: 三种可能的解决方

<script type="text/javascript">
//Quick & Dirty
var $text = "GBP 5 per hour";
var $arr = $text.match(/([a-z]{3}) (\d+(?:\.\d+)?) per ?(\d+)?\s?(hours?|days?|minutes?)/im);
console.log( $arr )
var $arrTmp = []
for( var $i = 0; $i < $arr.length; $i++ )
    if( typeof $arr[$i] != 'undefined' )
        $arrTmp.push( $arr[$i] )
$arr = $arrTmp;
console.log( $arr );

//Different approach
var $text = "GBP 5 per hour";
var $text1 = "GBP 5 per 10 hours";
var $regEx = /([a-z]{3}) (\d+(?:\.\d+)?) per(.*)(hours?|days?|minutes?)/im
var $arr = $text.match( $regEx );
var $arr1 = $text1.match( $regEx );

if( !isNaN( parseInt( $arr[3] ) ) )
    $arr[3] = parseInt( $arr[3] );
else
    $arr[3] = 1;
if( !isNaN( parseInt( $arr1[3] ) ) )
    $arr1[3] = parseInt( $arr1[3] );
else
    $arr1[3] = 1;


console.log( $arr1 );   
console.log( $arr );
</script>

undefined represents the place where the last digit you try to match should be ( per\\s?(\\d+) ) when the digit exists. undefined表示当数字存在时,您尝试匹配的最后一个数字应该是( per\\s?(\\d+) )。

To be coherent in any case, you should keep it, and maybe handle it as if it was a 1 . 为了在任何情况下一致,你应该保持它,也许处理它,仿佛它是一个1

If you prefer an empty string, you can try this one : 如果您更喜欢空字符串,可以试试这个:

"GBP 5 per hour".match(/([a-z]{3}) (\d+(?:\.\d+)?) per\s?([\d]*)\s?(hours?|days?|minutes?)/im)

I don't know if it's possible to directly get an array without it (I mean without filtering the array). 我不知道是否可以直接获取没有它的数组(我的意思是没有过滤数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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