Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 删除字符串后的逗号_Ruby - Fatal编程技术网

Ruby 删除字符串后的逗号

Ruby 删除字符串后的逗号,ruby,Ruby,我有以下格式的多个文件 文件:sample.txt id = class\234ha, class\poi23, class\opiuj, cap\7y6t5 dept = sub\6985de, ret\oiu87, class\234ha cko = cyr\hui87 我正在查找字符串并将其从多个文件中删除。例如,查找并删除字符串-class\234ha 我的代码工作正常,它删除了所有预期的字符串,但删除了预期的或标记的字符串后,行末尾有一个逗号 例如,删除字符串后的sample.txt

我有以下格式的多个文件

文件:sample.txt

id = class\234ha, class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87, class\234ha
cko = cyr\hui87
我正在查找字符串并将其从多个文件中删除。例如,查找并删除字符串-class\234ha

我的代码工作正常,它删除了所有预期的字符串,但删除了预期的或标记的字符串后,行末尾有一个逗号

例如,删除字符串后的sample.txt-class\234ha

id = class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87,
cko = cyr\hui87
我只想删除ret\oiu87,之后的最后一个逗号。对于多个文件,它应该是相同的。我不确定逗号后是否有新行字符或空格。我怎样才能使它工作。提前谢谢

代码


复杂正则表达式是邪恶的。除非您的应用程序域确实需要它们,否则不要使用它们。相反,要进行多次传递。我不太确定你想要的替代品是什么,但从结构上来说,这就是你想要做的:

# Create an interim string using your existing substitutions. For example,
# the corpus you currently have after substitutions contains:
tmp_str = <<~'EOF'
  id = class\poi23, class\opiuj, cap\7y6t5
  dept = sub\6985de, ret\oiu87, 
  cko = cyr\hui87EOF
EOF

# Remove trailing commas.
final_str = tmp_str.gsub /,\s*$/m, ''

puts final_str

使用这种方法,不管您是逐行工作还是在多行字符串上工作。无论哪种方式,都只是在每行末尾去掉逗号和尾随空格。简单

正如你建议的那样,我早就试过了,但没有成功。我现在已经在问题中列出了我的全部代码。非常感谢您查看我的查询。我已经修改了代码,您建议在正则表达式中包含*是关键。非常感谢。对不起,我不能投票,因为我没有足够的声誉
# Create an interim string using your existing substitutions. For example,
# the corpus you currently have after substitutions contains:
tmp_str = <<~'EOF'
  id = class\poi23, class\opiuj, cap\7y6t5
  dept = sub\6985de, ret\oiu87, 
  cko = cyr\hui87EOF
EOF

# Remove trailing commas.
final_str = tmp_str.gsub /,\s*$/m, ''

puts final_str
id = class\poi23, class\opiuj, cap\7y6t5
dept = sub\6985de, ret\oiu87
cko = cyr\hui87EOF