简体   繁体   English

正则表达式匹配任何一个词,但准确的词

[英]Regex match either word, but the exact word

i'm struggling figure out a regex.我正在努力找出一个正则表达式。 I want to replace a space with a dash but only if the following word matches either class or series .我想用破折号替换空格,但前提是以下单词与classseries匹配。

I have tried the following:我尝试了以下方法:

/\s(?=[^\s]*(class|series)$)/gi

'  E-Class' => ' -E-Class'
'E Class'   => 'E-Class'
' E Class'  => ' E-Class'

Above is close, but if there is already a dash it puts one before, which it shouldn't.上面很接近,但如果已经有一个破折号,它会在前面放一个,这是不应该的。

我相信你应该只匹配课堂或系列之前的空间,而不是之前的每个空间,这样你就可以尝试这样的事情:

/\s(class|series)$/gi

设法弄清楚,这按预期工作:

/\\s(?=class|series)/gi

Since you have [^\\s]* (No-Spaces) inside your positive look ahead, every word which ends in class or series (like E-Class or abcdefclass ) matches your positive look ahead.由于您的正面展望中有[^\\s]* (无空格),因此以classseries结尾的每个单词(如E-Classabcdefclass )都与您的正面展望相匹配。 If you only want to replace the space in front of class and series you can simply remove that and use /\\s(?=(class|series)$)/gi如果你只想替换classseries前面的空格,你可以简单地删除它并使用/\\s(?=(class|series)$)/gi

Following regex does the job as described by the OP ...下面的正则表达式完成了 OP 所描述的工作......

/\\s(?=class|series)|\\s(\\w+-?)+(?=class|series)/gi . /\\s(?=class|series)|\\s(\\w+-?)+(?=class|series)/gi .

Actually it's two separate regular expressions, one ( \\s(?=class|series) ) for the obviously simple case of matching the pattern of eg ' E Class' , the other one ( \\s(\\w+-?)+(?=class|series) ) for the more complex patterns such as eg ' E-Class' or ' Ee-ef-fooSeries' where the OP wants to "... replace a space with a dash but only if the following word [contains] either class or series " ( contains and not matches ; see my first comment above).实际上它是两个单独的正则表达式,一个 ( \\s(?=class|series) ) 用于匹配例如' E Class'的模式的明显简单情况,另一个 ( \\s(\\w+-?)+(?=class|series) ) 用于更复杂的模式,例如' E-Class'' Ee-ef-fooSeries' ,其中 OP 想要“...用破折号替换空格,但' Ee-ef-fooSeries'是以下单词[包含] classseries包含但匹配;请参阅我上面的第一条评论)。

The regex' match result needs to be handled by a custom replacer function.正则表达式的匹配结果需要由自定义替换函数处理。 A test case might look similar to the next provided one ...测试用例可能看起来类似于下一个提供的测试用例......

 const testEntries = [ // OP's request. [' E-Class', ' -E-Class'], ['E Class', 'E-Class'], [' E Class', ' E-Class'], // Bonus test. [' Ee-eClass', ' -Ee-eClass'], [' Ee-ef-Class', '-Ee-ef-Class'], [' Ee-ef-fooSeries', ' -Ee-ef-fooSeries'], ]; const regX = (/\\s(?=class|series)|\\s(\\w+-?)+(?=class|series)/gi); function didPassTest([value, expectedValue]) { return ( value.replace(regX, (match) => '-' + match.trim() ) === expectedValue ); } console.log( 'testEntries.every(didPassTest) ?..', testEntries.every(didPassTest) );

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

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