【问题标题】:Matching multiple input values in regex匹配正则表达式中的多个输入值
【发布时间】:2010-09-04 22:45:17
【问题描述】:

我有以下输入值,我希望有人能告诉我匹配所有“值”(217、218、219)的最佳方法——html 被转义,这就是我需要匹配的。

<input type=\"hidden\" name=\"id\" value=\"217\"\/>

<input type=\"hidden\" name=\"id\" value=\"218\"\/>

<input type=\"hidden\" name=\"id\" value=\"219\"\/>

【问题讨论】:

  • 或者哪个IDE? [愚蠢的评论最小长度限制!]
  • 所有行都在一个字符串中吗?还是从文件中读取?
  • Javascript,用于 jMeter 测试。从 JSON 响应中读取。所以单行

标签: javascript html regex


【解决方案1】:

根据您对其他响应的 cmets,您实际上只想匹配符合模式 name=\"id\" value=\"###\" 的数字,因此有四种可能性,具体取决于您希望匹配的精确程度。另外,根据您的 cmets,我使用 javascript 作为实现语言。

另外,请注意之前的答案错误地转义了 id 和 value 字符串周围的斜线。

FWIW,我已经测试了以下每个选项:

选项 1:匹配任意数字

//build the pattern
var pattern = /name=\"id\" value=\"([0-9]+)\"/g

//run the regex, after which:
//  the full match will be in array_matches[0]
//  the matching number will be in array_matches[1]
var array_matches = pattern.exec(strVal);

选项 2:匹配任何 3 位数字

//build the pattern
var pattern = /name=\"id\" value=\"([0-9]{3})\"/g

//run the regex, after which:
//  the full match will be in array_matches[0]
//  the matching number will be in array_matches[1]
var array_matches = pattern.exec(strVal);

选项 3:匹配特定的 3 位数字范围

//build the pattern; modify to fit your ranges
//  This example matches 110-159 and 210-259
var pattern = /name=\"id\" value=\"([1-2][1-5][0-9])\"/g

//run the regex, after which:
//  the full match will be in array_matches[0]
//  the matching number will be in array_matches[1]
var array_matches = pattern.exec(strVal);

选项 4:匹配特定的 3 位数字

//build the pattern; modify to fit your numbers
//  This example matches 217, 218, 219 and 253
var pattern = /name=\"id\" value=\"(217|218|219|253)\"/g

//run the regex, after which:
//  the full match will be in array_matches[0]
//  the matching number will be in array_matches[1]
var array_matches = pattern.exec(strVal);

【讨论】:

  • @UltraVi01:JGB146 正确回答了您,除非您现在告诉我们,在同一个字符串中,您可能有其他 HTML 标记包含格式为 name="id" value="nnn" 的属性,这些属性未输入标签,如文本区域或复选框或文本。在这种情况下,您需要使正则表达式更加具体,例如: var pattern = /
【解决方案2】:

我不知道使用什么语言,但假设您显示的代码是一个字符串(因为您已转义所有引号),您可以将该字符串传递到以下将匹配任何数字序列的正则表达式。

/([0-9]+)/g

根据您使用的语言,您需要移植此正则表达式并使用正确的函数。

在 JS 中你可以使用:

var array_matches = "your string".match(/([0-9]+)/g);

在 PHP 中你可以使用:

preg_match("([0-9]+)", "your string", array_matches);

【讨论】:

  • 我应该提到:应该有数字的文档还有更多...我需要将其缩小到 name=\"id\" value=
  • @UltraVi01:然后 JGB146 正确回答了你,在那里阅读我的 cmets 到他的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
  • 2017-10-08
  • 2019-06-19
相关资源
最近更新 更多