Home > Enterprise >  Split string to groups with regex
Split string to groups with regex

Time:06-29

I had 6 strings:
[db1 db2] /my/first/path/ /second/optional/path/
[db1 db2] /my/first/path/
--all /my/first/path/ /second/optional/path/
--all /my/first/path/
db /my/first/path/ /second/optional/path/
db /my/first/path/

Is it possible to create regex to split each of this strings to 2 groups (or 3 groups if optional path is added)

CodePudding user response:

Try using the following regex:

^([^\/] ) (\/\S ) ?(\/. )?

Explanation:

  • ^: the start of string symbol
  • ([^\/] ): Group 1, composed of any character other than a slash
  • : a space
  • (\/\S ): Group 2, composed of a slash and any non space character
  • ?: an optional space
  • (\/. )?: Group 3 (optional), composed of what remains of the string (any character)
  • Related