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

发布于 2024-12-03 20:47:13 字数 576 浏览 2 评论 0原文

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

我知道我不应该为此使用正则表达式,但这是我唯一的 html 的单一情况,所以......

我如何从上面的字符串中获取“4,13”?

编辑

上下文:

我正在通过 jQuery TableSorter 对表进行排序。一列包含 html 格式的数据,我无法更改它。我正在编写的自定义解析器有一个格式函数,我目前使用它来管理货币、百分比等...

现在,我想使用正则表达式检查收到的字符串是否是一个字符串。

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

how can I get "4,13" from the string above?

EDIT

Context:

I am sorting a table via jQuery TableSorter. A column contains that html-formatted data and I can't change it. 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);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱冒险 2024-12-10 20:47:13

这应该适用于您的具体示例 -

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);

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

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/

如歌彻婉言 2024-12-10 20:47:13

编辑

如果您只想匹配数字

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

请参阅Regexr 上的此处

匹配可选的 +或 - 然后至少一位数字,然后是带有 . 的可选分数。或 a , 作为分数分隔符。

/Edit

尝试类似这样的操作

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

,然后您将在捕获组 1 中找到值“+4,13”。

请参阅 Regexr 上的此处

如果您想排除 + 而不是在捕获组之前添加它(可能是可选的)

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

Edit

If you just want to match numbers

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

See it here on 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.

See it here on Regexr

If you want to exclude the + than add it (maybe optional) before the capturing group

<font color="green">\+?([^<]+)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文