javascript如何匹配整个单词,但在一定的长度限制

时间:2018-05-09 17:39:48

标签: javascript regex match string-length

例如我有这两个字符串:

字符串1:

"hi sir may name is Jone"

字符串2

 "hi may name is Jone"

我有这个正则表达式:

     var regex = XRegExp('hi(?:(?!hi|Jone).)*?Jone', 'gs');

会匹配他们两个,但我想修改正则表达式只匹配整个字符串的有限长度

我想匹配字符串2"你可能名字是Jone"因为文字长度较少怎么办..

2 个答案:

答案 0 :(得分:0)

如果你想只使用正则表达式匹配整个字符串的有限长度,我想你可以这样做:

var index = 15;


var testString1 = "hi may name is Jone";
var testString2 = "hi sir may name is Jone";

testString1.match("^.{1," + index + "}Jone"); // This will match
testString2.match("^.{1," + index + "}Jone"); // This string is longer and will not match

正则表达式^.{1, n}Jone的解释。

^:应匹配字符串的开头。

.{1, n}Jone:匹配1到n之间的所有内容,直到模式完全匹配。

在这种情况下,我们将n定义为index,因此此“限制”可以是动态的。

希望这有帮助!

答案 1 :(得分:0)

如果你想获得与你的正则表达式匹配的字数最少的字符串,你可以split并使用空格作为分隔符并检查返回数组的长度。

作为一个字符串数组的示例,您可以创建var longestString = "";,它将在循环的末尾包含最短的匹配字符串。

在循环中,首先检查是否有match并且longestString是否为空字符串。如果是这种情况,那么设置变量,这样就可以匹配未来可能的匹配。

var strings = [
  "test",
  "hi sir may name is Jone",
  "hi may name is Jone",
  "hi Jone",
  "hi may name is Jone test",
  "hi i am Jone",
  "may name is Jone test",
  "hi may name is Jane test test 2"
];

var regex = /hi(?:(?!hi|Jone).)*?Jone/;
var longestString = "";

strings.forEach((str) => {
  var match = XRegExp.match(str, regex);
  if (match && longestString === "") {
    longestString = str;
    return;
  }
  if (match && str.split(" ").length < longestString.split(" ").length) {
    longestString = str;
  }
});
console.log(longestString);
<script src="https://unpkg.com/xregexp/xregexp-all.js"></script>