Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何使用正则替换图片 URL 上的尺寸规格? #16

Open
liangbus opened this issue Dec 4, 2019 · 0 comments
Open

如何使用正则替换图片 URL 上的尺寸规格? #16

liangbus opened this issue Dec 4, 2019 · 0 comments
Labels

Comments

@liangbus
Copy link
Owner

liangbus commented Dec 4, 2019

每次开发遇到正则,都是直接网上找,很少自己写,终于这次遇到了要自己手写正则的问题,毫无意外地跪了,当时也是因为紧张脑子不太好使,回来反思了一下,然后自己尝试写了一下,也是可以写出来的,唉~

要替换的图片 url 示例

https://www.abcd.com/th234erest/path/hash_hah234ei40a512hasdf-630x630.png

解释之前先贴一个学习正则的链接
ziishaned/learn-regex - github

其目标就是要替换掉上面的 630x630 这一字符串
(其实这个场景确实是挺常见的,算是实战题型了)

思路:
确认 630x630 的这个字符串的规律,中间是一个 x 两边是数字,这时就可以写

/(\d)(x)(\d)/
// test:
var reg1 = new RegExp(/(\d)(x)(\d)/)
reg1.test('120x120') // true
reg1.test('0x0') // true
reg1.test('0ax0') // false
reg1.test('abdck123mx0ax0') // false

基本能匹配上了,但是并不完善,再来修改一下,明确 x 两边的数字长度,因为是图片规格,所以一般尺寸是 2-4 位(太小不需要替换,过大应该是录入问题,更应该暴露问题吧)

/(\d){2,4}(x){1}(\d){2,4}/
// test
var reg2 = new RegExp(/(\d){2,4}(x){1}(\d){2,4}/)
reg2.test('hash-ahahasdkjfhasdjhb-330x330') // true
reg2.test('hash-ahah9x9ab-9x330') // false
reg2.test('hash-ahah550x550ab-9x10') // true 但这并不是我们想要的

图片前面有个 hash 串,里面如果刚好包含了类似规格的字符串,那么就会匹配上,但是这并不是我们想要的,所以,再来优化一下
(-){1}(\d){2,4}(x){1}(\d){2,4}\.
规格前面必须是一个横杠,后面必须是一个点,一般图片的 hash 串中不会带这种特殊字符,所以这样匹配应该是不会有问题的了
微信截图_20191204110321

推荐一个有助于学习正则的网站:regex101.com

@liangbus liangbus added the RegExp label Dec 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant