[英]Regex to find certain characters in a string
I'm doing this in Javascript, so there might be an easier way? 我正在使用Javascript进行此操作,因此可能会有更简单的方法? However I have a string that looks like this:
但是我有一个看起来像这样的字符串:
designs/<random_id>/<random_id>/icon_<random_id>.png
An example of this would be: 例如:
designs/DMFSx881yveor8qolW7DUuPxWDQ2/e53BqQG2Y3wnn8uVRw8m/icon_a5898064.png
What I want to do is to check to see if this string ends with icon_<random_id>.png
If it does, do X, otherwise do nothing 我要做的是检查此字符串是否以
icon_<random_id>.png
结尾。如果是,请执行X,否则不执行任何操作
I'm not very good at Regex. 我对Regex不太好。 I've tried
^icon\\_{*}\\.png$
but I'm not having a lot of joy 我已经尝试过
^icon\\_{*}\\.png$
但是我没有很多乐趣
That one matches your use case : 那个符合您的用例:
\/icon_(\w+)\.png$
Then you can do something like : 然后,您可以执行以下操作:
var matches = str.match(/\/icon_(\w+)\.png$/g);
You can use this code to simple check is the partial exist or not : 您可以使用此代码简单检查部分是否存在:
let reg = /(icon_[\S]+\.png)$/iu;
let str = 'designs/DMFSx881yveor8qolW7DUuPxWDQ2/e53BqQG2Y3wnn8uVRw8m/icon_a5898064.png';
let check = str.match(reg);
if(Array.isArray(check) && check[0]) {
console.log('exists');
}else{
console.log('not exists');
}
I would think something like /(icon_[A-z0-9]+.png)$/
might be what you're looking for. 我想您可能正在寻找类似
/(icon_[A-z0-9]+.png)$/
东西。
var img-reg = /(icon_[A-z0-9]+.png)$/;
var url = 'designs/DMFSx8uPxWDQ2/e53BqQG2Y3wnn8uVRw8m/icon_a58598064.png';
if (img-reg.test(url)) {
//do something because it matched.
}
icon_ + any amount of numbers or letters followed by .png and the $ represents that it has to be at the end of the string. icon_ +任意数量的数字或字母,后跟.png,而$表示它必须在字符串的末尾。 when you use a ^ at the beginning you state that the start has to match too.
当您在开头使用^时,您指出起点也必须匹配。
此正则表达式可以满足您的目的:
^.*icon\_[a-z,0-9]*\.png$
/icon\\_[A-z0-9]{8}\\.png/
tested with regex101.com . 经过regex101.com测试。 It also provides a good explanation of how the regex works.
它还为正则表达式的工作原理提供了很好的解释。
if x = 'your string'
y = x.match(/\/icon_[^/]+.png/);
if this return value to y then x string you needed 如果此返回值为y,则需要使用x字符串
您可以使用以下正则表达式:
designs\\/[A-Za-z0-9]*\\/[A-Za-z0-9]*\\/icon_[A-Za-z0-9]*.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.