ruby - Regex for optional quotes, array of hashes and empty string -
I want to write a regular expression to accept the following types of ruby -
1) "Value1"
2) 'value2'
3) "" or "'
4) [{: this =>: that is, I have the following: "= & gt;: This}, {'foo' = & gt;: bar}, {: bar = & gt; 'Foo'}]
/ P>
regex = / (["']?) ([^' ']] [?] [^' ']] <1 / With that problem, he does not accept empty stars - "" and "".
Can you recommend any options or improvements?
I do not know whether regex uses flavor Ruby, but assuming it is somewhat perl-compatible:
regex = / (["']) (?: \\.:. ) ?? 1 / demo:
This expression will allow you to avoid quotation in your string "like \" "" . The trick here is to use an alternative like this. The second part of the alternative ( ) will never be able to match backslash. And the non-greedy quasifier ensures that the backrefence will match the ending quote.
Edit: In fact, I think I can forget the fourth point in your question. If you want to regex to match the values of values, then you have to create something else. .. Like Parser , like this: (? Value> (? & Lt; string & Gt; (? & Lt; Bid & gt; [']] (?: \\. |) *? \ K gt; \ s * = & gt; \ s * \ g & lt; value & gt; ; \ S *), \ s *) * \ g | \ s *) \}) | \ [(?: (?: \ S * \ g S *, \ s *) * \ g | \ s *) \]) demo:
This expression actually contains strings There will also be matte arrays. Note that I did not include anything for numbers because you do not mention them.
If you want to match only the hash specifically, then you can change the above expression in a small amount:
(? & Lt; value & gt; (? & Lt; string & gt; (? & Lt; quote & gt; ["']) (?: \\. |) *? \ K & lt ; Citation & gt; |:: \ w +) | (? & Lt; hash & gt; \ {(? :(? :(? & Lt; hashitem & gt; \ s * \ g gt; \ S * = & gt; \ s * \ g , \ s *), \ s *) * \ g | \ s *) \}) | [[ :: (?: \ S * \ g & lt; hash & gt; \ s *, \ s *) * \ g | \ s *) \]) I 'will extend it to your needs.
Comments
Post a Comment