iT邦幫忙

1

[發問] RegExp 燒燒腦! 將 href="styles.css 取代成 href="/home/styles.css 保留 href="/static/styles.css

Ami 2022-08-10 15:03:44661 瀏覽
  • 分享至 

  • xImage

RegExp大哉問! 一起跟大家燒燒腦

var string = `
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="/static/styles.css">
`

將 href=" (非 href="/ 開頭) 的路徑加入/home

string.replaceAll(????, ???)

最終結果要

<link rel="stylesheet" href="/home/styles.css">
<link rel="stylesheet" href="/static/styles.css">

求求大神們解惑!

froce iT邦大師 1 級 ‧ 2022-08-10 15:35:35 檢舉
^styles.css$

限定開頭結尾不就好了?
Ami iT邦新手 4 級 ‧ 2022-08-10 15:42:21 檢舉
這只是個範例~ 並不是永遠styles.css
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
akitect
iT邦新手 5 級 ‧ 2022-08-10 16:05:29
最佳解答

不會 JS,只會 Python

import re

string = """
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="/static/styles.css">
"""

pattern = '(href=")([^\/])'
replacement = '\g<1>/home/\g<2>'
sub_string = re.sub(pattern, replacement, string)

print(sub_string)
# sub_string
<link rel="stylesheet" href="/home/styles.css">
<link rel="stylesheet" href="/static/styles.css">

() 分成兩個 group,第二個 group 條件為 字元非/,最後兩個 group 之間插入 /home/


新增亂刻的 JS: (2022-08-10 16:53:29)

var string = `
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="/static/styles.css">
`

console.log(string.replaceAll(/(href=")([^/])/g, "$1/home/$2"));
<link rel="stylesheet" href="/home/styles.css">
<link rel="stylesheet" href="/static/styles.css">
Ami iT邦新手 4 級 ‧ 2022-08-11 11:07:36 檢舉

感謝您~ 這個思路很明瞭
大有收穫~

以下是我自己研究出來的方法也提供給你

string.replaceAll(/href="(?!\/)(.+?)"/ig, 'href="/home/$1"')

[^/] 這個方法我也有想到
但他一直會把我不要的's'也選進去

沒想到還有([^/])這個解法
/images/emoticon/emoticon42.gif

1
wiseguy
iT邦超人 1 級 ‧ 2022-08-10 19:02:39

akitect 的答案已經可以做到。不過發問看起來像是作業,老師想要的答案比較可能會是這個:

string.replaceAll(/href="(?!\/)/g, 'href="/home/');

(?! 這個語法是看看後面接的字是什麼。有符合才算整個RE符合。

Ami iT邦新手 4 級 ‧ 2022-08-11 11:04:40 檢舉

感謝~

主要是自己在解問題
想看看有大家怎麼解這個正則式
並不是作業喔

目前自己研究出來的是

string.replaceAll(/href="(?!\/)(.+?)"/ig, 'href="/home/$1"')

透過$1 可以對path做一些應用

我要發表回答

立即登入回答