简体   繁体   中英

Regex to find certain characters in a string

I'm doing this in Javascript, so there might be an easier way? 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

I'm not very good at Regex. I've tried ^icon\\_{*}\\.png$ but I'm not having a lot of joy

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.

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. 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 . It also provides a good explanation of how the regex works.

  • icon matches the characters icon literally (case sensitive)
  • _ matches the character _ literally (case sensitive)
  • Match a single character present in the list below [A-z0-9]{8}
  • {8} Quantifier — Matches exactly 8 times
  • Az a single character in the range between A (index 65) and z (index 122) (case sensitive)
  • 0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
  • . matches the character . literally (case sensitive)
  • png matches the characters png literally (case sensitive)
if x = 'your string'
y = x.match(/\/icon_[^/]+.png/);

if this return value to y then x string you needed

您可以使用以下正则表达式:

designs\\/[A-Za-z0-9]*\\/[A-Za-z0-9]*\\/icon_[A-Za-z0-9]*.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM