I don't know much about Ruby, but I have this line of code that I would like to know what it exactly does:

newline.gsub!(/\s+(های)\s+/,'‌\1 ')

I appreciate any help on this.

有帮助吗?

解决方案

The regular expression matches if a string contains the persian phrase with one or more whitespace characters around it (both at the front and back).

Then it replaces it with the string \1. The \1 refers to the first matched element. So, it removes all the whitespace around the string and adds one space after the element.

Example

I am taking the value test instead of the Parsi phrase, because unicode wasn't working out.

newline = "    test   "
=> "    test   "
newline.gsub!(/\s+(test)\s+/,'\1 ') 
=> "test "

其他提示

The documentation says:

gsub!(pattern, replacement) → str or nil

So your expression would return the substituted string if it matched the pattern, else return nil. (Essentially remove all the whitespaces before the farsi string and replace the ones following it with a single whitespace.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top