我想在字符串中用下划线替换空白,以创建良好的url。例如:
"This should be connected"
应该成为
"This_should_be_connected"
我使用Python和Django。这可以用正则表达式解决吗?
我想在字符串中用下划线替换空白,以创建良好的url。例如:
"This should be connected"
应该成为
"This_should_be_connected"
我使用Python和Django。这可以用正则表达式解决吗?
当前回答
perl -e 'map { $on=$_; s/ /_/; rename($on, $_) or warn $!; } <*>;'
匹配和替换当前目录下所有文件的空格>下划线
其他回答
x = re.sub("\s", "_", txt)
你不需要正则表达式。Python有一个内置的string方法,可以满足你的需要:
mystring.replace(" ", "_")
使用re模块:
import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And so\tshould this') # And_so_should_this
除非上面有多个空格或其他空格,否则您可能只希望使用string。按照其他人的建议替换。
使用字符串的replace方法:
“这应该是有联系的”。Replace (" ", "_")
“this_should_be_disconnected”。Replace ("_", " ")
OP使用python,但在javascript中(这是要小心的,因为语法是相似的。
// only replaces the first instance of ' ' with '_'
"one two three".replace(' ', '_');
=> "one_two three"
// replaces all instances of ' ' with '_'
"one two three".replace(/\s/g, '_');
=> "one_two_three"