英文:
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("https://images.dog.ceo/breeds/husky/n02110185_11841.jpg"))
console.log(extractBreed("https://images.dog.ceo/breeds/chihuahua/n02110185_11841.jpg"))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论