Ruby条带表达式的正则表达式

时间:2022-12-16 15:45:01

I need to write a regular expression for lines of expression such as these:

我需要为表达式行编写正则表达式,例如:

constraint :name, 'name != nil'
constraint :name, 'name =~/^[A-Z]/'
constraint :age, 'age >= 0'

A line always contains the word "constraint :", and any word can come after ":" followed by ",".

一行总是包含单词“constraint:”,任何单词都可以在“:”后跟“,”。

A conditional expression will then appear inside ' '.

然后条件表达式将出现在''中。

I have written a regex like this:

我写了一个像这样的正则表达式:

/^constraint :(\w*),'(.*)'$/

And it doesn't match. I am new to Ruby and regular expression. Can anyone please help me?

它不匹配。我是Ruby和正则表达的新手。谁能帮帮我吗?

1 个解决方案

#1


3  

You forgot the space after the comma. Try /^constraint :(\w*), '(.*)'$/

你忘了逗号后面的空格。尝试/ ^约束:(\ w *),'(。*)'$ /

Although to be more general, I'd go with this: /^constraint :([^,]+),\s*'(.*)'$/.

虽然更一般,但我会选择:/ ^约束:([^,] +),\ s *'(。*)'$ /。

#1


3  

You forgot the space after the comma. Try /^constraint :(\w*), '(.*)'$/

你忘了逗号后面的空格。尝试/ ^约束:(\ w *),'(。*)'$ /

Although to be more general, I'd go with this: /^constraint :([^,]+),\s*'(.*)'$/.

虽然更一般,但我会选择:/ ^约束:([^,] +),\ s *'(。*)'$ /。