简体   繁体   English

ruby on rails,如果它是*符号,则替换最后一个字符

[英]ruby on rails, replace last character if it is a * sign

I have a string and I need to check whether the last character of that string is *, and if it is, I need to remove it. 我有一个字符串,我需要检查该字符串的最后一个字符是否为*,如果是,我需要将其删除。

if stringvariable.include? "*"
 newstring = stringvariable.gsub(/[*]/, '')
end

The above does not search if the '*' symbol is the LAST character of the string. 以上不会搜索'*'符号是否是字符串的最后一个字符。

How do i check if the last character is '*'? 我如何检查最后一个字符是否为'*'?

Thanks for any suggestion 谢谢你的任何建议

Use the $ anchor to only match the end of line: 使用$ anchor仅匹配行尾:

"sample*".gsub(/\*$/, '')

If there's the possibility of there being more than one * on the end of the string (and you want to replace them all) use: 如果字符串末尾有可能存在多个*(并且您想要全部替换它们),请使用:

"sample**".gsub(/\*+$/, '')

You can also use chomp ( see it on API Dock ), which removes the trailing record separator character(s) by default, but can also take an argument, and then it will remove the end of the string only if it matches the specified character(s). 您也可以使用chomp在API Dock上查看 ),它默认删除尾随记录分隔符,但也可以接受参数,然后只有当它与指定的字符匹配时才会删除字符串的结尾(S)。

"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"
"hello*".chomp("*")      #=> "hello"

String has an end_with? 字符串有一个end_with? method 方法

stringvariable.chop! if stringvariable.end_with? '*'

You can either use a regex or just splice the string: 您可以使用正则表达式或只拼接字符串:

if string_variable[-1] == '*'
  new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end

That only works in Ruby 1.9.x... 这只适用于Ruby 1.9.x ...

Otherwise you'll need to use a regex: 否则你需要使用正则表达式:

if string_variable =~ /\*$/
  new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end

But you don't even need the if : 但你甚至不需要if

new_string = string_variable.gsub(/\*$/, '')

You can do the following which will remove the offending character, if present. 您可以执行以下操作,如果存在,将删除有问题的字符。 Otherwise it will do nothing: 否则它什么都不做:

your_string.sub(/\*$/, '')

If you want to remove more than one occurrence of the character, you can do: 如果要删除多个字符,可以执行以下操作:

your_string.sub(/\*+$/, '')

Of course, if you want to modify the string in-place, use sub! 当然,如果要在原地修改字符串,请使用sub! instead of sub 而不是sub

Cheers, Aaron 干杯,亚伦

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM