【问题标题】:How do I write a regular expression that brings specific characters?如何编写带特定字符的正则表达式?
【发布时间】:2021-12-31 07:31:16
【问题描述】:

当以下字符串存在时,我想从内部提取特定字符串。我要提取的字符串是uuid。

但是不知道怎么填写正则表达式带上uuid。 uuid前后除了'/'和'-'怎么写?

const text = "hello_img/2021/12/27/uuid-c.jpg";
const reg = /\b\/u.*?-/g;
const matches = text.match(reg);
  
console.log(matches);

【问题讨论】:

  • 试试:/\bu[^-]+/
  • 我们是在谈论 uuid 作为字符串,还是将 uuid 替换为真正的 uuid?
  • 比如我写了uuid,真的是uuid。它可能是 v3。
  • 你能举一些具体的例子吗(有很多变化)?
  • 对于外行,就像我现在一样,“UUID”=Universally unique identifier

标签: javascript regex


【解决方案1】:

在最后一次出现 / 之后获取文本,这似乎是您想要的:

const url = "hello_img/2021/12/27/f189f4ae-af11-11e7-b252-186590cec0c1-helloworld.jpg";
console.log(url.split("/").pop());

输出将是

f189f4ae-af11-11e7-b252-186590cec0c1-helloworld.jpg

要删除.jpg,您可以使用

newUrl = url.replace('.jpg','');

【讨论】:

  • 谢谢。有这样一个简单的方法,但我想我只想到了正则表达式。
【解决方案2】:

如果您想在最后一次出现 / 之后匹配 uuid 的实际格式,那么您可以匹配 / 并捕获捕获组 1 中的格式,然后匹配除 / 之外的任何字符,直到字符串的结尾。

 \/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b[^\/\r\n]*$

Regex demo

const text = "hello_img/2021/12/27/f189f4ae-af11-11e7-b252-186590cec0c1-helloworld.jpg";
const reg = /\/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b[^\/\r\n]*$/;
const m = text.match(reg);
if (m) {
  console.log(m[1]);
}

【讨论】:

  • 感谢您让我知道一顿丰盛的正餐。新年快乐!
猜你喜欢
  • 2016-11-15
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 2022-10-04
  • 2011-02-20
相关资源
最近更新 更多