gpt4 book ai didi

javascript - 如何使用正则表达式获取最后一个模式

转载 作者:行者123 更新时间:2023-11-30 00:06:44 28 4
gpt4 key购买 nike

var a = 'a.b.c.d.e.f'
a = a.split('.');
var len = a.length;
var pattern = a[len-2]+'.'+a[len-1]
console.log(pattern);

它工作得非常好,但我必须使用正则表达式来做,有没有办法我们可以使用正则表达式获得相同的结果

或任何其他方式,这将是仅获取最后 2 个用点 (.) 字符分隔的字符串的有效解决方案。

最佳答案

您可以使用正则表达式来查找由点分隔的最后一个字符。

/[^.]+\.[^.]+$/
  • [^.]+ match a single character not present in the list below

    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]

    . the literal character .

  • \. matches the character . literally

  • [^.]+ match a single character not present in the list below

    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]

    . the literal character .

  • $ assert position at end of the string

console.log('a.b.c.d.e.f'.match(/[^.]+\.[^.]+$/, ''));
console.log('zz.yy.xx.ww.vv.uu'.match(/[^.]+\.[^.]+$/, ''));
console.log('number with.dot'.match(/[^.]+\.[^.]+$/, ''));

关于javascript - 如何使用正则表达式获取最后一个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38218639/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com