简体   繁体   English

正则表达式捕获最后一个空格字符和字符串结尾之间的字符

[英]Regex to capture characters between the last white space character and the end of string

I'm trying to determine the characters between the last white space characer and the end of the string. 我正在尝试确定最后一个白色空间字符和字符串结尾之间的字符。

Example

Input:   "this and that"

Output: "that"

I have tried the regex below but it doesnt work! 我试过下面的正则表达式,但它不起作用!

var regex = /[\s]$/

Can do without regex 可以没有正则表达式

var result = string.substring(string.lastIndexOf(" ")+1);

Using regex 使用正则表达式

result = string.match(/\s[a-z]+$/i)[0].trim();

I suggest you to use simple regex pattern 我建议你使用简单的正则表达式模式

\S+$

Javascript test code: Javascript测试代码:

document.writeln("this and that".match(/\S+$/));

Output: 输出:

that 

Test it here . 在这里测试一下

You could just remove everything up to the last space. 您可以删除所有内容到最后一个空格。

s.replace(/.* /, '')

Or, to match any white space... 或者,匹配任何空白区域......

s.replace(/.*\s/, '')

Your example matches just one space character at the end of the string. 您的示例仅匹配字符串末尾的一个空格字符。 Use 使用

/\s\S+$/

to match any number. 匹配任何数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM