正则表达式:将所有内容匹配到最后一个空格,而不包括它 [英] RegEx: Match everything up to the last space without including it

查看:432
本文介绍了正则表达式:将所有内容匹配到最后一个空格,而不包括它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串中的所有内容匹配到最后一个空格,但不包括它.例如,我想匹配放在粗体中的字符:

I'd like to match everything in a string up to the last space but without including it. For the sake of example, I would like to match characters I put in bold:

RENATA T. GROCHAL

到目前为止,我有 ^(.+\s)(.+) 但是,它与最后一个空格匹配,我没有不想.正像我一样,RegEx也应该适用于英语以外的其他语言.

So far I have ^(.+\s)(.+) However, it matches the last space and I don't want it to. RegEx should work also for other languages than English, as mine does.

编辑:我没有提到第二个捕获组不应包含空格-它应该是GROCHAL而不是GROCHAL之前有空格.

I didn't mention that the second capturing group should not contain a space – it should be GROCHAL not GROCHAL with a space before it.

基于两个答案提供的新RegEx是: ^((.+)(?=\s))\s(.+) ,用于替换匹配项的RegEx为\3, \1.它达到了预期的结果:

EDIT 2: My new RegEx based on what the two answers have provided is: ^((.+)(?=\s))\s(.+) and the RegEx used to replace the matches is \3, \1. It does the expected result:

GROCHAL, RENATa T.

任何改进都是可取的.

推荐答案

^(.+)\s(.+)

带有替换字符串:

\2, \1

更新:

另一个可以折叠两个捕获组之间多余空间的版本:

Another version that can collapse extra spaces between the 2 capturing groups:

^(.+?)\s+(\S+)$

这篇关于正则表达式:将所有内容匹配到最后一个空格,而不包括它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆