javascript 正则表达式匹配某些单词周围的任何2或3位数字,但不直接跟随该单词[关闭]

4urapxun  于 2023-11-15  发布在  Java
关注(0)|答案(2)|浏览(105)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
18小时前关门了。
Improve this question
字符串:
“有艾米,艾米16岁,身高167,还有杰森,杰森18岁,身高185。”

**Regex匹配Amy的年龄和身高,但不匹配Jason的。

于是:

16 - match 
167 - match 
18 - no match 
185 - no match

字符串
我想用正则表达式来搜索\d{2,3}和查找单词'Amy',但我找不到。单词'Amy'也不能匹配。
如果它不能在单个表达式中完成,我也希望看到它在JavaScript中具有额外的逻辑。

j5fpnvbx

j5fpnvbx1#

希望它能解决你的问题。
您可以在正则表达式中使用lookbehind和lookaheadAssert的组合来实现这一点。下面是针对您的特定情况的正则表达式:

(?<!\wAmy\s)\b(\d{2,3})\b(?!\scm)

字符串
让我们分解这个正则表达式的组件:

  1. (?<!\wAmy\s):否定后看Assert。它Assert当前位置之前的不是单词字符(\w)后跟“Amy”和空白字符(\s)
  2. \b:单词边界,确保匹配整个单词而不是部分匹配。
  3. (\d{2,3}):捕获2位或3位的组。
  4. \b:另一个单词边界。
  5. (?!\scm):否定先行Assert。它Assert当前位置后面的字符不是后跟“cm”的空白字符。
    在JavaScript中,可以如下使用这个正则表达式:
const regex = /(?<!\wAmy\s)\b(\d{2,3})\b(?!\scm)/g;
const input = "There was Amy. Amy was 16 years old and she was 167 cm tall. And also there was Jason. Jason was 18 years old and he was 185 cm tall";

let match;
while ((match = regex.exec(input)) !== null) {
  console.log(match[1]);
}


这将输出:

16
167


这确保了正则表达式匹配2位或3位数字,这些数字不是直接在单词“Amy”之前,也不是后跟“cm”。

syqv5f0l

syqv5f0l2#

我只忽略任何代词,句子的结构必须像你写的那样

const getNameAgeHeight = (str, name) => {
  const regex = new RegExp(`${name}\\s+was\\s+(\\d+)\\s+years\\s+old\\s+and\\s+.*?\\s+was\\s+(\\d+)\\s+cm\\s+tall`, "i");
  const match = str.match(regex);

  if (match) {
    const [_, age, height] = match;
    return { name, age, height };
  }
  return null; // nothing found
}

const str = "There was Amy. Amy was 16 years old and she was 167 cm tall. And also there was Jason. Jason was 18 years old and he was 185 cm tall";
let name = "Amy";
console.log(getNameAgeHeight(str, name))

name = "Jason";
console.log(getNameAgeHeight(str, name))

字符串
这里有一个更通用的

const regex = /(\w+)\s+was\s+(\d{1,3})\s+years\s+old.*?(\d{1,3})\s+cm/g;

const getDetails = str => {
  let match;
  let peopleData = {};

  while ((match = regex.exec(str)) !== null) {
    const [_, name, age, height] = match;
    console.log(name,age, height)
    peopleData[name] = {
      age,
      height
    };
  }

  return peopleData
}

const str = "There was Amy. Amy was 16 years old and she was 167 cm tall. And also there was Jason. Jason was 18 years old and he was 185 cm tall";

console.log(getDetails(str)["Amy"])

相关问题