正则表达式用于从字符串中提取数字。

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

Regular expression for extract numbers from the string

问题

I need to extract numbers from the string for that I have preferred the following regex

var str = "1 1/2 percentage";
var n = str.match(/[0-9]+([\/.]\d+)?/g);
console.log(n);

But I am not able to restrict negative numbers in the string .

Valid Scenario:

"1.5 % dividend applied"
"1 1/2 percentage"
"1/10 percentage"
"2.5 percentages"
"10% dividend"
"10 percentages applied"

Invalid Scenario:

"-1 1/2 percentage"
"-1.5 % dividend applied"
"-10% dividend"

Code suggestion will be appreciated. Thank you.

英文:

I need to extract numbers from the string for that I have preferred the following regix

var str = "1 1/2 percentage";
var n = str.match(/[0-9]+([\/.]\d+)?/g);
console.log(n);

But I am not able to restrict negative numbers in the string .

Valid Scenario:

"1.5 % dividend applied"
"1 1/2 percentage"
 "1/10 percentage"
"2.5 percentages"
"10% dividend"
"10 percentages applied"

Invalid Scenario:

"-1 1/2 percentage"
"-1.5 % dividend applied"
"-10% dividend"

Code suggestion will be appriciated.Thank you

答案1

得分: 3

以下是您要翻译的内容:

(?<![-.\d])           # 匹配不以'-'、'.'或数字开头的内容,
\d+(?:\.\d+)?         # 以数字开头,可包含小数点,
(?:\/\d+(?:\.\d+)?)?  # 可选地跟着'/'和类似于第一个的另一个数字。

您可以在 regex101.com 上尝试

尝试它:

// 隐藏: true 控制台: false babel: false

// 语言: lang-js

console.config({ maximize: true });

const testcases = [
  '1.5 % dividend applied',
  '1 1/2 percentage',
  '1/10 percentages',
  '2.5 percentages',
  '10% dividend',
  '18.6 foo',
  '10 percentages applied',
  '-1 1/2 percentage',
  '-1.5 % dividend applied',
  '-10% dividend',
  '-18.6 foo',
  '2.25/150 bar'
];

const regex = /(?<![-.\d])\d+(\.\d+)?(?:\/\d+(\.\d+)?)?/g;

for (const testcase of testcases) {
  console.log(`'${testcase}'`, testcase.match(regex) ?? 'no match');
}
<!-- 语言: lang-html -->

<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

原始答案:

(?&lt;![-.\d])   # 匹配不以'-'、'.'或数字开头的内容,
\d+           # 以1个或更多数字开头,
([\/.]\d+)?   # 以'/'或'.'后跟1个或更多数字结尾

您可以在 regex101.com 上尝试

英文:

You need:

(?&lt;![-.\d])           # Match something that is not preceded by &#39;-&#39;, &#39;.&#39; or a digit,
\d+(?:\.\d+)?         # starts with a number, with or without decimal places,
(?:\/\d+(?:\.\d+)?)?  # optionally followed by &#39;/&#39; and another number similar to the first.

Try it on regex101.com.

Try it:

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

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

console.config({ maximize: true });

const testcases = [
  &#39;1.5 % dividend applied&#39;,
  &#39;1 1/2 percentage&#39;,
  &#39;1/10 percentages&#39;,
  &#39;2.5 percentages&#39;,
  &#39;10% dividend&#39;,
  &#39;18.6 foo&#39;,
  &#39;10 percentages applied&#39;,
  &#39;-1 1/2 percentage&#39;,
  &#39;-1.5 % dividend applied&#39;,
  &#39;-10% dividend&#39;,
  &#39;-18.6 foo&#39;,
  &#39;2.25/150 bar&#39;
];

const regex = /(?&lt;![-.\d])\d+(\.\d+)?(?:\/\d+(\.\d+)?)?/g;

for (const testcase of testcases) {
  console.log(`&#39;${testcase}&#39;`, testcase.match(regex) ?? &#39;no match&#39;);
}

<!-- language: lang-html -->

&lt;script src=&quot;https://gh-canon.github.io/stack-snippet-console/console.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

Original answer

You need:

(?&lt;![-.\d])   # Match something that is not preceded by &#39;-&#39;, &#39;.&#39; or a digit,
\d+           # starts with 1+ digits, and
([\/.]\d+)?   # ends with either a &#39;/&#39; or a &#39;.&#39; followed by 1+ digits

Try it on regex101.com.

Try it:

<!-- begin snippet: js hide: true -->

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

console.config({ maximize: true });

const testcases = [
  &#39;1.5 % dividend applied&#39;,
  &#39;1 1/2 percentage&#39;,
  &#39;1/10 percentages&#39;,
  &#39;2.5 percentages&#39;,
  &#39;10% dividend&#39;,
  &#39;18.6 foo&#39;,
  &#39;10 percentages applied&#39;,
  &#39;-1 1/2 percentage&#39;,
  &#39;-1.5 % dividend applied&#39;,
  &#39;-10% dividend&#39;,
  &#39;-18.6 foo&#39;
];

const regex = /(?&lt;![-.\d])\d+([\/.]\d+)?/g;

for (const testcase of testcases) {
  console.log(`&#39;${testcase}&#39;`, testcase.match(regex) ?? &#39;no match&#39;);
}

<!-- language: lang-html -->

&lt;script src=&quot;https://gh-canon.github.io/stack-snippet-console/console.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

答案2

得分: 0

用JavaScript和正则表达式混合编写的代码如下:

function getNumbers(text) {
    // 匹配所有数字
    var matches = text.match(/-?\d+([\/.]\d+)?/g);
    var res = [];

    for (var i = 0; i &lt; matches.length; i++) {
        var match = matches[i];

        if (!match.startsWith('-')) { // 检查是否为负数
            res.push(match);
        }
    }

    return res;
}
英文:

With a mix of javascript and regex:

function getNumbers(text) {
    //match all numbers
    var matches = text.match(/-?\d+([\/.]\d+)?/g);
    var res = [];

    for (var i = 0; i &lt; matches.length; i++) {
        var match = matches[i];

        if (!match.startsWith(&#39;-&#39;)) { // check if its not a negative number
            result.push(match);
        }
    }

    return res;
}

huangapple
  • 本文由 发表于 2023年5月22日 13:58:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76303370.html
匿名

发表评论

匿名网友

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

确定