简体   繁体   English

基于正则表达式组的 Typescript 中从后面出现的数字拆分字符串

[英]Split string based on digits occurring from behind in Typescript based on regex group

I am trying to split a string which is of the following format -我正在尝试拆分以下格式的字符串-

text = "some random words 22 minutes go some text that follows". text = "一些随机单词 22 分钟 go 一些随后的文本"。 I am only concerned about "some random words".我只关心“一些随机词”。

The text can have 'minute' or 'hour' or 'hours' in it.文本中可以包含“分钟”或“小时”或“小时”。 I want to split and get the string that is before the digits.我想拆分并获取数字之前的字符串。 I cannot split based on digits only because the initial part can have digits too.我不能仅基于数字进行拆分,因为初始部分也可以有数字。

I tried to handle this with split and if conditions.我试图用 split 和 if 条件来处理这个问题。 But those are not fast enough.但这些还不够快。 I am struggling to deal this with typescript regex group.我正在努力处理 typescript 正则表达式组。 Any suggestions would be very helpful任何建议都会非常有帮助

The function that I used was -我使用的 function 是 -

export function splitstring(msg: string): string 
{
  if (msg.includes('minute')) 
  {
    return msg.toLowerCase().split('minute')[0];
  }
  if (msg.includes('minutes')) 
  {
    return msg.toLowerCase().split('minutes')[0];
  }
  if (msg.includes('hour')) 
  {
    return msg.toLowerCase().split('hour')[0];
  }
  if (msg.includes('hours')) 
  {
    return msg.toLowerCase().split('hours')[0];
  }
  return msg;
}

Sounds like you can use .match(/(.*)\W\d+\W(minute|hour)/)[1]听起来你可以使用.match(/(.*)\W\d+\W(minute|hour)/)[1]

 var text = "some random words 22 minutes go some text that follows"; console.log( text.match(/(.*)\W\d+\W(minute|hour)/)[1] ) var text = "some random words 22 inute go some 12 hours text that follows"; console.log( text.match(/(.*)\W\d+\W(minute|hour)/)[1] ) var text = "some 18 random words 22 minutes go 11 some text that follows"; console.log( text.match(/(.*)\W\d+\W(minute|hour)/)[1] )

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

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