只包括数字在结果中

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

Regex Regular Expression - Only include numbers in result

问题

"Result:" ex. VAT) £112.49
"Desired Result:" 112.49

英文:

I am trying to extract only the numbers after a specific string Total (ex. VAT) £112.49. I have started learning regex today and getting stuck. I have got it returning the value I want but it is also showing some letters also.

只包括数字在结果中

Here is the regex query: ex.*?\d+(?:\.\d+)?

Here is the data:

Sub total (inc. VAT)	£134.99
VAT	£22.50
Total (inc. VAT)	£134.99
Total (ex. VAT)	£112.49:
  • Result: ex. VAT) £112.49
  • Desired Result: 112.49

I have also attached a screenshot for reference.

答案1

得分: 1

你可以使用捕获组并使模式更具体:

  • \( 匹配 (
  • ex\. 匹配 ex.
  • [^()]* 匹配可选的除 () 之外的字符
  • \) 匹配 )
  • \s* 匹配可选的空白字符
  • £ 匹配文字 £
  • (\d+(?:\.\d+)*) 第 1 组,1 个或更多数字,可选的小数部分
  • \b 单词边界

或者使用 \D* 来匹配可选的非数字字符,然后捕获数字:

  • \( 匹配 (
  • ex\. 匹配 ex.
  • [^()]* 匹配可选的除 () 之外的字符
  • \) 匹配 )
  • \s* 匹配可选的空白字符
  • \D* 匹配可选的非数字字符
  • (\d+(?:\.\d+)*) 第 1 组,1 个或更多数字,可选的小数部分
  • \b 单词边界
英文:

You could make use of a capture group and make the pattern a bitmore specific:

\(ex\.[^()]*\)\s*£(\d+(?:\.\d+)*)\b

Explanation

  • \( Match (
  • ex\. Match ex.
  • [^()]* Match optional chars other than ( or )
  • \) Match )
  • \s* Match optional whitespace chars
  • £ Match literally
  • (\d+(?:\.\d+)*) Group 1, 1+ digits with an optional decimal part
  • \b A word boundary

Regex demo

Or use \D* to match optional non digits before capturing the digits:

\(ex\.[^()]*\)\s*\D*(\d+(?:\.\d+)*)\b

Regex demo

答案2

得分: 0

以下是已翻译好的部分:

只提供您希望匹配的静态文本,并使用数字的模式。
此外,您将希望将您希望捕获的值放在一个 捕获组 内,也称为子表达式。

"我试图提取特定字符串 Total (ex. VAT) £112.49 后面的数字。"

Total \(ex\. VAT\) +£(\d+\.\d+)

第一个组将返回以下内容。

112.49
英文:

Just provide the static text you're looking to match, and utilize a pattern for the number.

Additionally, you'll want to place the value you're looking to capture, within a capture group—also referred to as a sub-expression.

> "I am trying to extract only the numbers after a specific string Total (ex. VAT) £112.49."

Total \(ex\. VAT\) +£(\d+\.\d+)

Group 1 will return the following.

112.49

huangapple
  • 本文由 发表于 2023年6月1日 00:28:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375595.html
匿名

发表评论

匿名网友

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

确定