不知道這是否可能......但我需要查找(並替換)字符串內的所有逗號,我將在PHP代碼文件上運行這些逗號。即類似於"[^"]+,[^"]+"
之類的東西,除了它也會在字符串的錯誤一側進行搜索(第一個引號是字符串結束的地方,最後一個是開頭的地方)。如有必要,我可以多次運行它以獲取所有逗號。我試圖在Komodo中使用查找和替換功能。這是一項一次性工作。在字符串中查找逗號?
那麼,這是我的腳本到目前爲止,但它是不正確的。在小測試文件上工作,但在完整文件中替換字符串之外的逗號。呸。
import sys, re
pattern = ','
replace = '~'
in_str = ''
out_str = ''
quote = None
in_file = open('infile.php', 'r')
out_file = open('outfile.php', 'w')
is_escaped = False # ...
while 1:
ch = in_file.read(1)
if not ch: break
if ch in ('"',"'"):
if quote is None:
quote = ch
elif quote == ch:
quote = None
out_file.write(out_str)
out_file.write(re.sub(pattern,replace,in_str))
in_str = ''
out_str = ''
if ch != quote and quote is not None:
in_str += ch
else:
out_str += ch
out_file.write(out_str)
out_file.write(in_str)
in_file.close()
out_file.close()
類似的[SO問題](http://stackoverflow.com/questions/249791/regexp-for-quoted-string-with-escaping-quotes) - 這是不一個簡單的任務與正則表達式。 – nevets1219 2011-04-07 00:31:25
聽起來像解析一個逗號給我。如果吐()就夠了。不,我不這麼認爲。哦,你需要一個真正的專家來表達正則表達式,因爲你的要求不會停止這樣做,是嗎? – sln 2011-04-07 01:20:14
@sln:不,分割肯定是不夠的,因爲它不會在字符串文字內搜索。你甚至明白我在問什麼?我其實很擅長正則表達式,但他們不太適合這類問題,... – mpen 2011-04-07 06:28:03