如何在以相同符号开头和结尾但每次之间的数字都不同的文本中搜索值?节点JS
How to search for value in text which is starting and ending with the same symbol but the numbers between are different every time? NodeJS
我想搜索、查找并仅保留短信中特定字符串的数字,该值始终以 <@ 开头并以 结尾>。它的str总是21,<@和>[=之间的数字39=]每次都在变化,位置不固定,可以在短信的任意位置。
我现在在做什么:
if (message.content.includes('<@')) {
let numberPattern = /\d+/g;
let onlyNumbers = message.content.match(numberPattern).toString();
...
如果文字是这样的:
Hello <@371362419361972245> how are you?
onlyNumbers 变量将正确地为:
371362419361972245
但是如果文字是这样的:
Hello <@371362419361972245> h0w 4r3 y0u?
onlyNumbers 变量将是:
3713624193619722450430
我想做的是只保留 <@ 和 > 之间的数字。
正则表达式将是一个很好的应用。为了将来的参考,构建正则表达式的好工具是 regex101.com.
你想要的正则表达式看起来像
/<@(\d+)>/
如果您想在单个字符串中支持该模式的多个此类实例,您可以在该模式的末尾添加 g
标志。
要确定 <@
和 >
字符之间的数字,请使用 RegExp.prototype.exec(),这将 return 一个类似于以下内容的数组:
[
"<@371362419361972245>", // The full string that matched the pattern
"371362419361972245", // The first (and only) matching group
]
如果你想支持 g
标志,你将对同一个字符串多次执行相同的方法,直到它 return 为 null。
我想搜索、查找并仅保留短信中特定字符串的数字,该值始终以 <@ 开头并以 结尾>。它的str总是21,<@和>[=之间的数字39=]每次都在变化,位置不固定,可以在短信的任意位置。
我现在在做什么:
if (message.content.includes('<@')) {
let numberPattern = /\d+/g;
let onlyNumbers = message.content.match(numberPattern).toString();
...
如果文字是这样的:
Hello <@371362419361972245> how are you?
onlyNumbers 变量将正确地为:
371362419361972245
但是如果文字是这样的:
Hello <@371362419361972245> h0w 4r3 y0u?
onlyNumbers 变量将是:
3713624193619722450430
我想做的是只保留 <@ 和 > 之间的数字。
正则表达式将是一个很好的应用。为了将来的参考,构建正则表达式的好工具是 regex101.com.
你想要的正则表达式看起来像
/<@(\d+)>/
如果您想在单个字符串中支持该模式的多个此类实例,您可以在该模式的末尾添加 g
标志。
要确定 <@
和 >
字符之间的数字,请使用 RegExp.prototype.exec(),这将 return 一个类似于以下内容的数组:
[
"<@371362419361972245>", // The full string that matched the pattern
"371362419361972245", // The first (and only) matching group
]
如果你想支持 g
标志,你将对同一个字符串多次执行相同的方法,直到它 return 为 null。