英文:
Regex to get the number between word and char
问题
我正在尝试从字符串中获取位于'text'单词和''字符之间的数字。我在regex101页面上尝试了我的正则表达式,在那里它能够工作,但在我的代码中我什么都没有得到。
const s = 'line0_text4_89yf9sd9afg977f8gds9g9fdg'
const regexToGetNumber = '/_text(.*?)_/gm';
const result = s.match(regexToGetNumber); // 但它是null
在这种情况下,我期望得到数字4。
英文:
I'm trying to get the number from string between '_text' word and '_' char.
I tried my regex on regex101 page and there it's working but in my code I didn't get anything.
const s = 'line0_text4_89yf9sd9afg977f8gds9g9fdg'
const regexToGetNumber = '/_text(.*?)_/gm';
const result = s.match(regexToGetNumber); // and it's null
In that case I expect the 4.
答案1
得分: 1
你主要问题在于你引用了表达式。String
原型没有 match
方法。它需要是一个正则表达式字面量或者 RegExp
对象。
你可以使用正向后顾和正向先行,将表达式 [^_]*
(零个或多个非下划线字符)包裹起来。
你可以通过解构结果数组来提取第一个匹配项。
const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = /(?<=_text)[^_]*(?= _)/gm;
const [value] = str.match(regexToGetNumber) ?? [];
console.log(value); // '4'
如果你有一个正则表达式字符串,你需要调用 RegExp
构造函数:
const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = new RegExp('(?<=_text)[^_]*(?= _)', 'gm');
const [value] = str.match(regexToGetNumber) ?? [];
console.log(value); // '4'
英文:
Your main issue is that you quoted the expression. The String
prototype does not have a match
method. It needs to be a regex literal or RegExp
object.
You can use a positive look-behind (?<=_text)
and a positive look-ahead (?=_)
and wrap the expression [^_]*
(zero or more non-underscores).
You can extract the first match with destructuring the result array.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = /(?<=_text)[^_]*(?=_)/gm;
const [value] = str.match(regexToGetNumber) ?? [];
console.log(value); // '4'
<!-- end snippet -->
If you have a regex string, you need to call the RegExp
constructor:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = new RegExp('(?<=_text)[^_]*(?=_)', 'gm');
const [value] = str.match(regexToGetNumber) ?? [];
console.log(value); // '4'
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论