正则表达式从最后一个单词中提取单词

问题描述 投票:0回答:2

我有一个类似的字符串-“您好,我的号码已创建200”

我必须提取数字200,我尝试了\ bis([\ s \ S] + $),但它拉了200个创建的数字

感谢您在这方面的帮助

regex space
2个回答
0
投票

此作品

const str = 'Hello my Number is 200 created'
const regex = /(\S+)\s\S+$/
const word = str.match(regex)[1]
console.log(word)

顺便说一句,不需要正则表达式,对于某些情况而言,这样可能更易于阅读

const str = 'Hello my Number is 200 created'
const words = str.split(' ')
const word = words[words.length-2]
console.log(word)

0
投票

您可以使用正则表达式

\w+(?=\W+\w+\W*$)

Demo

正则表达式引擎执行以下操作。

\w+    # match 1+ word chars
(?=    # begin a positive lookahead
  \W+  # match 1+ non-word chars (spaces, punctuation, etc.)
  \w+  # match 1+ word chars (last word in string)
  \W*  # match 0+ non-word chars (spaces, punctuation, etc.)
  $    # match end of string
)
© www.soinside.com 2019 - 2024. All rights reserved.