简体   繁体   English

在RegExp中处理不同的匹配项

[英]Processing different matches in a RegExp

I want to construct a RegExp that matches either the first letter of the first word, or the first letter of non-first words, but I want to be able to distinguish between these two kinds matches so I can process non-first-word matches differently. 我想构建一个RegExp ,它匹配第一个单词的第一个字母或非首字母的第一个字母,但我希望能够区分这两种匹配,以便我可以处理非首字匹配不同。

For example I want to always capitalise the first word and all other words apart from instances of "bam" that are not the first word. 例如,我想总是将第一个单词和除“bam”不是第一个单词的实例之外的所有其他单词大写。

How can I do this? 我怎样才能做到这一点?

function titleCase(title) {
    return title.replace(/\b(.)/g, (str, p1) => {         
         return p1.toUpperCase();
    });
}

titleCase('foo bar bam'); // Foo Bar Bam - but I want Foo Bar bam

You can put multiple regex pieces together like /(option 1)|(option 2)/g 您可以将多个正则表达式拼凑在一起,如/(option 1)|(option 2)/g

Then your callback will receive either of: 然后你的回调将收到以下任何一个:

callback(match, option1, undefined, offset, subject) // left side matched
callback(match, undefined, option2, offset, subject) // right side matched

Using this, your callback can look like: 使用此功能,您的回调可能如下所示:

(str, p1, p2) => {
    if( p1) ...
    else if( p2) ...
}

Here is an implementation of titleCase which will capitalize the first letter of every word-like element in the string. 这是titleCase一个实现,它将大写字符串中每个类似字的元素的第一个字母。

function titleCase(title) {
  return title.replace(/\b(\w)(.*?)\b/g, (match, g1, g2) => `${g1.toUpperCase()}${g2}`)
}
  1. In this example, /\\b(\\w)(.*?)\\b/g will match a word boundary ( \\b ) followed by a word character ( \\w ). 在此示例中, /\\b(\\w)(.*?)\\b/g \\b\\w )(。*?) \\b /\\b(\\w)(.*?)\\b/g将匹配单词边界( \\b ),后跟单词字符( \\w )。 We capture the first letter using the grouping (\\w) , and is used as g1 in the replace function. 我们使用分组(\\w)捕获第一个字母,并在replace函数中用作g1
  2. Then we capture the remaining portion of the word using the group (.*?) , which is referenced using g2 in the replacer. 然后我们使用组(.*?)捕获单词的剩余部分,该组在替换器中使用g2引用。
  3. Finally, a template string is used to capitalize the first letter group and concatenate the result with the remaining match of the word. 最后,模板字符串用于大写第一个字母组,并将结果与​​单词的剩余匹配连接起来。

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

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