在字符串中查找逗号?

时间:2011-04-06 23:47:29

标签: regex

不确定这是否可行......但我需要查找(并替换)字符串中的所有逗号,我将在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()

1 个答案:

答案 0 :(得分:3)

我试图在PHP代码中找到字符串文字(即代码中有人在引号之间指定字符串的位置:$ somevar =“somevalue”;)

在这种情况下,编写一小段解析代码比使用正则表达式更容易(因为在正则表达式中复杂化以区分开始字符串文字的引号和结束它的引号)。

一些伪代码:

inquote = false
while (!eof)
    c = get_next_character()
    if (c == QUOTE_MARK)
        inquote = !inquote
    if (c == COMMA)
        if (inquote)
            delete_current_character()
相关问题