正则表达式提取文本中的所有价格,其中价格将使用",“作为小数分隔符。没有数以千计的分离器,它们后面将是“UDS”。例如:
1500 USD
9 USD
0,53 USD
12,01 USD
^[^0]\d+(\,)?[0-9]{0,2} USD
它适用于:
1500 USD
12,01 USD
但它不适用于:
9 USD
0,53 USD
发布于 2019-06-14 10:24:49
在您的模式^[^0]\d+(\,)?[0-9]{0,2} USD
中,在本部分^[^0]
中,第一个^是断言字符串开始的锚点。
第二个^位于字符类的开头,其含义是不同的。它创建一个否定的字符类,这意味着它不能以0开头。
下面的部分(\,)?[0-9]{0,2}
是一个可选的组,用于匹配逗号(注意不必转义)和0-2位数。这样,像1,
这样的值也会匹配。
没有标记的语言,但如果支持正向和负向查找,则可以使用此模式提取文本中使用单词边界的价格,以防止数字和美元成为较大单词的一部分。(?<!\S)
断言,直接在左边的不是非空格字符。
如果您希望整个匹配而不仅仅是价格,您可以匹配美元,而不是使用积极的展望。
(?<!\S)\d+(?:,\d{1,2})?(?= USD\b)
另一种选择是使用捕获组而不是前瞻性。(?:^|\s)
断言字符串的开始或匹配空格字符。
(?:^|\s)(\d+(?:,\d{1,2})?) USD\b
发布于 2019-06-13 22:40:31
在JavaScript中
/^\d{1,}(,\d{2}){0,1} USD$/
var regex = /^\d{1,}(,\d{2}){0,1} USD$/;
// true result
console.log(regex.test('9 USD'));
console.log(regex.test('0,53 USD'));
console.log(regex.test('12,01 USD'));
console.log(regex.test('1500 USD'));
// false result
console.log(regex.test(' USD'));
console.log(regex.test('0,5,3 USD'));
console.log(regex.test('12,0124 USD'));
console.log(regex.test('1s500 USD'));
或在行动中:
% echo "1500 USD 9 USD 0,53 USD 12,01 USD" |sed -E 's/[0-9]+(,[0-9][0-9]){0,1} USD/TRUE/g'
TRUE TRUE TRUE TRUE
选项-E启用扩展正则表达式
发布于 2019-06-13 22:25:08
我猜这个简单的表达式会返回我们想要的东西:
([0-9,.]+)
不管我们可能拥有的其他文本内容,因为这里不需要验证,假设我们的价格是有效的。
RegEx电路
jex.im可视化正则表达式:
测试
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"([0-9,.]+)";
string input = @"500 USD 9 USD 0,53 USD 12,01 USD
1500 USD 12,01 USD 9 USD 0,53 USD 1500 USD 12,01 USD 9 USD 0,53 USD ";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
演示
const regex = /([0-9,.]+)/gm;
const str = `500 USD 9 USD 0,53 USD 12,01 USD
1500 USD 12,01 USD 9 USD 0,53 USD 1500 USD 12,01 USD 9 USD 0,53 USD `;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
https://stackoverflow.com/questions/56589203
复制相似问题