匹配正则表达式并仅返回结果的一部分?

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

JavaScript: Match a regex and return only part of the result?

问题

这会返回 150 calorie,但我想要的只是 150。可以尝试以下方法来仅使用正则表达式实现:

const t = "The 2 items contained 150 calories";
const match = t.match(/(\d+) calorie/);
const result = match ? match[1] : null;

// 现在,result 包含了所需的值,如果匹配成功的话

这段代码会返回匹配的数字部分 150,如果匹配失败,则 resultnull

英文:

I know this is possible but I can't find the answer with the Google keywords I'm using, so I'm asking this in the hope it helps someone else too.

I'd like to regex match a substring but only return part of that substring.

Here's my attempt:

const t = "The 2 items contained 150 calories";
t.match(/(\d+) calorie/g).replace(" calorie", "");

This returns 150 calorie but what I want is just 150.

I can hack it with t.match(/(\d+) calorie/g)[0].replace(" calorie", "") but perhaps there's a way to do it just with regexes?

答案1

得分: 1

你可以使用正则表达式前瞻

const t = "The 2 items contained 150 calories";
const result = t.match(/(\d+)(?= calorie)/g);
console.log(result);

如果您需要进一步解释或有其他问题,请告诉我。

英文:

You can use regex lookaheads:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const t = &quot;The 2 items contained 150 calories&quot;;
const result = t.match(/(\d+)(?= calorie)/g)
console.log(result);

<!-- end snippet -->

答案2

得分: 1

你几乎正确,尽管你不能在.match后使用.replace,因为后者返回一个类似数组的对象。移除g标志,并使用[1]获取第一个捕获组:

const t = "The 2 items contained 150 calories";
const num = t.match(/(\d+) calorie/)[1];
console.log(num);

顺便说一下,如果你担心字符串不匹配你的正则表达式,可以使用这个方式:

const t = "The 2 items contained 150 calories";
const m = t.match(/(\d+) calorie/);
const num = m ? m[1] : null;
console.log(num);

你也可以像@Live bug help解释的那样使用正向预查,但请注意,这不是在所有浏览器中都通用,特别是Safari。

英文:

You were close, although you can't use a .replace after a .match because the latter returns an array like object. Remove the g flag, and get the first capture group with [1]:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const t = &quot;The 2 items contained 150 calories&quot;;
const num = t.match(/(\d+) calorie/)[1];
console.log(num);

<!-- end snippet -->

BTW, if you are concerned about a string not matching your regex use this instead:

const t = &quot;The 2 items contained 150 calories&quot;;
const m = t.match(/(\d+) calorie/);
const num = m ? m[1] : null;
console.log(num);

You can also use a positive lookahead as @Live bug help explained, but please note that that is not universally supported, notably Safari.

答案3

得分: 0

我不懂JavaScript,但我认为正则表达式与Python中的相同。在我的示例中,'t'是您的文本字符串。

解释:

  • \d+ 匹配1个或更多数字(或\ d匹配单个数字)
  • (?:/\d+)? 可选地匹配/和1个或更多数字
  • (?= 正向前瞻,用于断言右侧紧接着的内容是
  • \s?calories?\b 匹配可选的空白字符,然后是calories或calories
  • ) 关闭前瞻

代码:

result = re.findall(r"\d+(?:/\d+)?(?=\s?calories?\b)", t)
print(result) # 只会打印150

来源:Stack Overflow

英文:

I don’t know JavaScript, but I think regex is equal as in python. In my example ‘t’ is your text string.

Explanation:

<li>\d+ Match 1+ digits (Or \d for a single digit) </li>
<li>(?:/\d+)? Optionally match / and 1+ digits </li>
<li>(?= Positive lookahead to assert what is directly at the right is </li>
<li>\s?calories?\b Match an optional whitspace char followed by calories or calories </li>
<li>) Close the lookahead
</li>

code:
<pre>
result = re.findall(r"\d+(?:/\d+)?(?=\s?calories?\b)", t)
print(result) # will print 150 only
</pre>

Source: Stack Overflow

huangapple
  • 本文由 发表于 2023年1月9日 06:27:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051705.html
匿名

发表评论

匿名网友

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

确定