ユーザーから整数を取得して開き、results[1]
という名前で保存するスクリプトがあります。reを使用して負の数を検索するにはどうすればよいですか?
次に、myfile.configを開き、文字列の後に整数を検索します。文字列はlocationID=
です。 だから、数の文字列は次のようになります。
locationID="34"
または任意の乱数があります。 現在の番号を結果の番号に置き換えます。
これまでのところ、スクリプトは数字があるかどうかをチェックし、locationID=
の後にリストされている数字がない場合はチェックします。
どうすれば負の数を確認して置き換えることができますか?ここで
はオリジナルです:
def replaceid:
source = "myfile.config"
newtext = str(results[1])
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
pattern = r'(?<=locationId=")\d+' # find 1 or more digits that come
# after the string locationid
if re.search(pattern, line):
sys.stdout.write(re.sub(pattern, newtext, line)) # adds number after locationid
fileinput.close()
else:
sys.stdout.write(re.sub(r'(locationId=)"', r'\1"' + newtext, line)) # use sys.stdout.write instead of "print"
# using re module to format
# adds a location id number after locationid even if there was no number originally there
fileinput.close()
これは私のために働いていません。
def replaceid:
source = "myfile.config"
newtext = str(results[1])
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
pattern = r'(?<=locationId=")\d+' # find 1 or more digits that come
# after the string locationid
patternneg = r'(?<=locationId=-")\d+'
if re.search(pattern, line):
sys.stdout.write(re.sub(pattern, newtext, line)) # adds number after locationid
fileinput.close()
elif re.search(patternneg, line): # if Location ID has a negative number
sys.stdout.write(re.sub(patternneg, newtext, line)) # adds number after locationid
fileinput.close()
else:
sys.stdout.write(re.sub(r'(locationId=)"', r'\1"' + newtext, line)) # use sys.stdout.write instead of "print"
# using re module to format
# adds a location id number after locationid even if there was no number originally there
fileinput.close()
re.sub( "locationId =([ - \ d] +)"、newtext、line)のようなものを試しましたか? – ginginsha
locationId = \ "( - ?\ d +)\"は、locationId = "34"とlocationId = " - 34"の両方に一致し、番号をグループとして持ちます。ここで確認できます:https://regex101.com/r/r3bRW6/2 –
パターン変数にその値を入力するにはどうすればよいですか?これは私の文書からlocationid文字列を完全に消去します:pattern = 'locationId = \ "( - ?\ d +)\"' – Prox