提取一个单词,使用正则表达式。

huangapple go评论136阅读模式
英文:

Extract 1 word using regex expression

问题

提取狗的品种的正则表达式为:breeds/(.*?)/

英文:

How to extract the breed of the dog from this url https://images.dog.ceo/breeds/husky/n02110185_11841.jpg ?
Considering the breed will change, what would be the regex expression to extract what's between breeds/ and the next '/'?

答案1

得分: 1

breeds\/([^\/]+) 应该符合您的要求。

然而,正则表达式似乎不适合这种情况。我建议您解析URL并从路径中提取所需的部分。

英文:

breeds\/([^\/]+) should match your requirements.

However, regular expressions do not seem to be the right fit for this case. I recommend you parse the URL and extract the desired part from the path.

答案2

得分: 0

以下是代码部分的翻译:

const regex = /https:\/\/images\.dog\.ceo\/breeds\/([^/]+)\//

function extractBreed(s) {
  var results = regex.exec(s);
  return results[1];
}

console.log(extractBreed("https://images.dog.ceo/breeds/husky/n02110185_11841.jpg"))
console.log(extractBreed("https://images.dog.ceo/breeds/chihuahua/n02110185_11841.jpg"))
英文:

You can use this regex since you know it will always be this website

The key is to recognise and discard the parts before the breed name, using \/ for the forward-slashes since they are normally delimiters for JS regexes, and then use the ( and ) to capture everything up to the next forward slash.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const regex = /https:\/\/images\.dog\.ceo\/breeds\/([^/]+)\//


function extractBreed(s) {
  var results = regex.exec(s);
  return results[1];
}

console.log(extractBreed(&quot;https://images.dog.ceo/breeds/husky/n02110185_11841.jpg&quot;))

console.log(extractBreed("https://images.dog.ceo/breeds/chihuahua/n02110185_11841.jpg"))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月6日 23:57:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定