匹配以前缀开头的子串 [英] Match substring that start with prefix

查看:40
本文介绍了匹配以前缀开头的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被一个小正则表达式困住了我正在尝试使用正则表达式匹配以给定前缀开头的每个子字符串在 JavaScript 中

I am stuck with a little regular expression I am trying to match every substring that start with a given prefix using regular expression in javascript

prefix = "pre-"
regex = /???/

"pre-foo-bar bar pre-bar barfoo".replace(regex, '')
// should output "bar barfoo"

推荐答案

/\bpre-\S*\s?/g 有效,假设您也想去除尾随空格(根据您的示例).如果您想保留它,请使用 /\bpre-\S*/g

/\bpre-\S*\s?/g works, assuming you want to strip out the trailing space as well (per your example). If you want to leave it in, use /\bpre-\S*/g

更正

\b 只查找单词字符,而 - 绝对不是单词字符.不幸的是,JavaScript 不支持自定义后视.

\b only looks up word characters, and - is definitely not a word character. Unfortunately, JavaScript doesn't support custom lookbehinds.

/(\s|^)pre-\S*/g 应该可以工作,但与上面给出的示例输出相比,会有一个前导空格.这会检查pre-"前面是空字符还是空格字符,然后是 0 个或多个非空格字符.它删除除了空间之外的整个块.如果空间对您来说真的很重要,您可以这样做:

/(\s|^)pre-\S*/g should work, but there will be a leading space compared to the example output given above. This checks for "pre-" preceded either by nothing or a space character and then followed by 0 or more non-space characters. It removes the whole block except the space. If the space is really important to you, you could do:

str.replace(/(\s|^)pre-\S*\s?/g, function(wholeString, optionalSpaceCharacter) {
    return optionalSpaceCharacter;
});

二次修正

如果您连续有两个,例如pre-a pre-b pre-c",我给您的复杂替换将不起作用.你会以 "pre-b " 结尾,因为最后有 \s? .获得确切所需输出的最佳选择是使用 /(\s|^)pre-\S*/g 并检查原始字符串是否以pre-"开头,如果是这样,只需从开头删除一个空格.

The complex replace I gave you won't work if you have two in a row like, "pre-a pre-b pre-c". You'll end up with "pre-b " because of the \s? at the end. Your best bet to get the exact desired output is to use /(\s|^)pre-\S*/g and check the original string if it started with "pre-" if so, just remove one space from the beginning.

str.replace(/(\s|^)pre-\S*/g, '').substring(str.substring(0, 4) == "pre-" ? 1 : 0);

这篇关于匹配以前缀开头的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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