正则表达式以获取单词和字符之间的数字

huangapple go评论63阅读模式
英文:

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 (?&lt;=_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 = &#39;line0_text4_89yf9sd9afg977f8gds9g9fdg&#39;;
const regexToGetNumber = /(?&lt;=_text)[^_]*(?=_)/gm;
const [value] = str.match(regexToGetNumber) ?? [];

console.log(value); // &#39;4&#39;

<!-- 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 = &#39;line0_text4_89yf9sd9afg977f8gds9g9fdg&#39;;
const regexToGetNumber = new RegExp(&#39;(?&lt;=_text)[^_]*(?=_)&#39;, &#39;gm&#39;);
const [value] = str.match(regexToGetNumber) ?? [];

console.log(value); // &#39;4&#39;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月12日 21:17:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定