0

In ruby:

"experience"[/.e/] 
=> "pe" 

Just like expected. However...

"experience"[/.*e/] 
=> "experience"

Is there a way to write a regular expression that returns to first/shorter version it comes across?

"experience"[regexp]
=> "expe"
Benjamin Lee
  • 1,014
  • 10
  • 24
  • Sorry for the duplicate. I had read that article and tried [.*?e], which wasn't what I was looking for. The answer is [.+?e] – Benjamin Lee Sep 24 '18 at 23:53
  • A better way of writing the regex might be the variant that also works in [possessive form](https://www.regular-expressions.info/possessive.html). This means being more specific in what you want to match. `/([^e]|\Ae)++e/` matches at least one character that is not an `e`, but also allows the `e` if it is at the start of the string. It keeps matching until an `e` is encountered and then matches that by having a trailing `e` in the regex. `"experience"[/([^e]|\Ae)++e/] #=> "expe"` – 3limin4t0r Oct 08 '18 at 17:36
  • [Here is the demo](http://rubular.com/r/5mBQxGdNGQ). I had to wrap it in an extra pair of parentheses since Rubular only shows the resulting groups. – 3limin4t0r Oct 08 '18 at 17:47

0 Answers0