所以我有一个文件,就像
2587, 1, 104, 971;
2586, 1, 104, 971;
2585, 1, 104, 971;
2584, 1, 104, 971;
2584, 1, 104, 971;
2584, 1, 104, 971;
2584, 1, 104, 971;
2584, 1, 104, 971;
2583, 1, 104, 971;
2582, 1, 104, 971;
2582, 1, 104, 971;
我必须将其更改为,
2587, 2, 104, 971;
2586, 2, 104, 971;
2585, 2, 104, 971;
2584, 2, 104, 971;
2584, 2, 104, 971;
2584, 2, 104, 971;
2584, 2, 104, 971;
2584, 2, 104, 971;
2583, 2, 104, 971;
2582, 2, 104, 971;
2582, 2, 104, 971;
我正在尝试使用正则表达式,但我无法选择第二列,我使用了这个,([^,.]*)
,任何指针?
答案 0 :(得分:1)
Python解决方案:
with open('filename') as f:
for line in f:
columns = line.rstrip().split(', ')
columns[1] = '2' #column[1] is the second column
print ", ".join(columns).rstrip()
如果文件不是很大:
import re
with open('filename') as f:
text = f.read()
print re.sub(r'(\d+,\s*)\d+,',r'\g<1>2,', text)
答案 1 :(得分:0)
在Notepad ++中,你可以这样做:
search what : ^(\d+, \s*)\d+,
replace with: ${1}2,
答案 2 :(得分:0)
String s = "2587, 1, 104, 971;\n"
+ "2586, 1, 104, 971;\n"
+ "2585, 1, 104, 971;\n"
+ "2584, 1, 104, 971; \n"
+ "2584, 1, 104, 971;\n"
+ "2584, 1, 104, 971;\n"
+ "2584, 1, 104, 971;\n"
+ "2584, 1, 104, 971;\n"
+ "2583, 1, 104, 971;\n"
+ "2582, 1, 104, 971;\n"
+ "2582, 1, 104, 971;";
Pattern p = Pattern.compile("\\d+,\\s*(\\d+),\\s*\\d+,\\s*\\d+;");
Matcher m = p.matcher(s);
while(m.find()) {
String output = m.group().replaceAll(m.group(1), "2");
System.out.println(output);
}
但我认为你不应该在这个过程中使用正则表达式。你可以在java中使用split方法然后改变数组的第二个元素。