我编写了一个RegExp,可以正确验证一种货币,例如EUR
或USD
:
const ccyRegEx = new RegExp(currencies.join('|'), 'i');
在给定EUR|USD|JPY|GBP...
的情况下,会产生类似currencies = ["EUR", "USD", "JPY", "GBP"...]
的东西
我将如何使用此RegExp和currencies
数组作为输入来构建新的RegExp来验证货币对,例如EURUSD
,USDJPY
?
currencies
数组很大,并且可能会发生变化,因此我想动态创建此正则表达式,而不是硬编码货币对的所有可能排列。
相同的货币对,例如EUREUR
和USDUSD
无效。
不同顺序的货币对有效,例如EURUSD
和USDEUR
。
答案 0 :(得分:3)
您只需添加{2}
即可完全匹配集合中的两项。
例如,/(a|b|c){2}/
将匹配ab
,ca
,而不是ad
。
您可以像这样更改动态正则表达式:
const currencies = ["EUR", "USD", "JPY", "GBP"];
const singleMatch = new RegExp(currencies.join('|'));
console.log('single match - EUR:', singleMatch.test('EUR'));
const doubleMatch = new RegExp('(' + currencies.join('|') + '){2}');
console.log('double match - EUR:', doubleMatch.test('EUR'));
console.log('double match - USDEUR:', doubleMatch.test('USDEUR'));
console.log('double match - GBPEUR:', doubleMatch.test('GBPEUR'));
console.log('double match - GBPGDD:', doubleMatch.test('GBPGDD'));
注意:它也与EUREUR
相匹配。为了避免这种情况,您应该使用负向后看或负向前看。
正如他在评论部分中所述,我集成了@PJProudhon否定性提前实现。
const currencies = ["EUR", "USD", "JPY", "GBP"];
const doubleMatch = new RegExp('(?:(' + currencies.join('|') + ')(?!\\1)){2}');
console.log('double match - EUREUR:', doubleMatch.test('EUREUR')); //expect false
谢谢@PJProudhon
答案 1 :(得分:2)
我想让它保持简单愚蠢,并构建具有所有可能性的中间数组,例如:
const currenciesPair = [];
const currenciesLength = currencies.length
for (let i = 0; i < currenciesLength ; i++) {
for (let j = 0; j < currenciesLength ; j++) {
// avoiding pair such as EUREUR, USDUSD, etc...
if (i !== j) {
currenciesPair.push(currencies[i] + currencies[j]);
}
}
}
并使用此数组保留正则表达式(您也可以将currencyPair和Currency混合使用以实现完全可能性):)
答案 2 :(得分:1)
虽然这是一种效率很低的算法,所以根据货币数量的不同,其他选择会更好。
如果对数据集可行,我希望使用CristianTraìna的解决方案。
const currencies = [ "EUR", "USD", "JPY", "GBP" ];
const product_matrix = currencies // loop over all the currencies
.map( currency => currencies // We want to join the currency with all other currencies
.map( pair => currency !== pair // Only do the join if the currency and its pair aren't the same
? `${ currency }${ pair }`
: null )
.filter( Boolean ) // Remove all the null values. YOu coudl use reduce instead of map to skip this step.
)
.flat(); // Flatten the 2 dimensional array into a one dimensional one.
console.log( product_matrix );