简体   繁体   English

JavaScript RegEx,用于从HTML标记中提取值

[英]JavaScript RegEx for extracting value from HTML tag

<font color="green">+4,13</font>% 

I know that I shouldn't use regular expressions for that, but that's a single case where my only html is that so... 我知道我不应该为此使用正则表达式,但这只是我唯一的html就是这种情况。

how can I get "4,13" from the string above? 如何从上面的字符串中获取 “ 4,13”?

EDIT 编辑

Context: 内容:

I am sorting a table via jQuery TableSorter. 我正在通过jQuery TableSorter对表进行排序。 A column contains that html-formatted data and I can't change it. 一列包含该html格式的数据,我无法更改。 The custom parser I'm writing has a format function, which I currently use for managing currency, percentages and so on... 我正在编写的自定义解析器具有格式化功能,目前我用于管理货币,百分比等。

Now, I want to check, with a regex, if the string that comes to me is a string. 现在,我想用正则表达式检查出现在我身上的字符串是否是字符串。

format: function(s) {
    console.log(s);
    var stripped = s.replace("<font>","")
                     .replace("</font>", "");
    return jQuery.tablesorter.formatFloat(stripped);
}

This should work for your specific example - 这应该适用于您的特定示例-

var tagtext = '<font color="green">+0.00</font>%';
var keepplusorminus = false;
var myregexp = keepplusorminus ? /[-\+,\.0-9]+/ : /[,\.0-9]+/;
var match = myregexp.exec(tagtext);
if (match != null) {
    result = match[0];
} else {
    result = "";
}
alert(result);

Working demo - http://jsfiddle.net/ipr101/LHBp7/ 工作演示-http: //jsfiddle.net/ipr101/LHBp7/

Edit 编辑

If you just want to match numbers 如果您只想匹配数字

[+-]?\d+(?:[,.]\d+)?

See it here on Regexr 在Regexr上查看

Matches for an optional + or - then at least one digit, then an optional fraction with a . 匹配一个可选的+或-,然后至少一位,然后是一个可选的小数,并带有。 or a , as fraction delimiter. 或,作为分数定界符。

/Edit /编辑

Try something like this 试试这个

<font color="green">([^<]+)

You will then find the value "+4,13" in the capturing group 1. 然后,您将在捕获组1中找到值“ +4,13”。

See it here on Regexr 在Regexr上查看

If you want to exclude the + than add it (maybe optional) before the capturing group 如果要排除+不是在捕获组之前添加(可能是可选的)

<font color="green">\+?([^<]+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM