简体   繁体   English

正则表达式清理字符串

[英]Regular expression to clean string

I'm struggling to figure out even where to start with this. 我正在努力弄清楚从哪里开始。 I believe there is a regular expression to make this a fairly straight forward task. 我相信有一个正则表达式可以使这成为一个相当直接的任务。 I want to trim off the extra asterisks in a string. 我想修剪字符串中多余的星号。

Example string: 示例字符串:

test="AM*BE*3***LAST****~"

I would like it to trim asterisks off only the end that don't have repeating symbols. 我希望它只在没有重复符号的末端剪掉星号。 So the resulting value in the variable would be: 因此,变量中的结果值为:

test="AM*BE*3***LAST~"

In Perl I was able to use this: 在Perl中,我可以使用此功能:

s/\*+~+/~/;

Is there something similar I can do in Ruby? 我可以在Ruby中做类似的事情吗? I'm sure there is, just struggling to find it for some reason. 我敢肯定有,只是由于某种原因而努力找到它。 Any help would be greatly appreciated. 任何帮助将不胜感激。

You could use this regex: 您可以使用此正则表达式:

/\*+~$/

Then use the gsub method to replace all matches with a tilde ~ : 然后使用gsub方法用波浪号~替换所有匹配项:

test = "AM*BE*3***LAST****~"

test.gsub!(/\*+~$/, '~')
# => "AM*BE*3***LAST~"

Or you could use this more flexible regex, which matches any amount of characters after * until end of line: 或者,您可以使用这种更灵活的正则表达式,它匹配*之后直到行尾的任意数量的字符:

/\*+([^*])+$/

Then use the first capture group ( $1 ) as the replacement: 然后使用第一个捕获组( $1 )作为替换:

test.gsub(/\*+([^*])+$/) { $1 }

Ruby's String class has the [] method, which lets us use regexp as a parameter. Ruby的String类具有[]方法,该方法使我们可以使用regexp作为参数。 We can also assign to that, allowing us to do things like: 我们还可以分配给它,使我们可以执行以下操作:

foo = "AM*BE*3***LAST****~"
foo[/\*+~+$/] = '~'
foo # => "AM*BE*3***LAST~"

That reuses the match pattern from your Perl search/replace. 这将重用Perl搜索/替换中的匹配模式。 (I'm assuming you only want to match at the end of the line because of your examples. If it needs to be anywhere in the string remove the trailing $ from the pattern.) (由于您的示例,我假设您只希望在行的末尾进行匹配。如果它需要在字符串中的任何位置,请从模式中删除尾随的$ 。)

You can use Rubular and try to test the regex and achieve what you need based on the references down the page. 您可以使用Rubular并尝试测试正则表达式,并根据页面上的引用来实现所需的功能。

http://rubular.com/ http://rubular.com/

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

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