Regex get text before and after a hyphen

人盡茶涼 提交于 2019-12-08 03:01:25

If you cannot use look-behinds, but your string is always in the same format and cannout contain more than the single hyphen, you could use

^[^-]*[^ -] for the first one and \w[^-]*$ for the second one (or [^ -][^-]*$ if the first non-space after the hyphen is not necessarily a word-character.

A little bit of explanation: ^[^-]*[^ -] matches the start of the string (anchor ^), followed by any amount of characters, that are not a hyphen and finally a character thats not hyphen or space (just to exclude the last space from the match).

[^ -][^-]*$ takes the same approach, but the other way around, first matching a character thats neither space nor hyphen, followed by any amount of characters, that are no hyphen and finally the end of the string (anchor $). \w[^-]*$ is basically the same, it uses a stricter \w instead of the [^ -]. This is again used to exclude the whitespace after the hyphen from the match.

This is quite simple:

.*(?= - )     # matches everything before " - "
(?<= - ).*    # matches everything after " - "

See this tutorial on lookaround assertions.

Another solution is to string split on the hyphen and remove white space.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!