How do I use RegEx to pick longest match?

后端 未结 3 1410
灰色年华
灰色年华 2020-12-19 02:33

I tried looking for an answer to this question but just couldn\'t finding anything and I hope that there\'s an easy solution for this. I have and using the following code i

3条回答
  •  青春惊慌失措
    2020-12-19 03:07

    If you already know the lengths of the words beforehand, then put the longest first. For example:

    String pattern = ("(hello world|hello)");
    

    The longest will be matched first. If you don't know the lengths beforehand, this isn't possible.

    An alternative approach would be to store all the matches in an array/hash/list and pick the longest one manually, using the language's built-in functions.

提交回复
热议问题