简体   繁体   English

javascript 中的正则表达式对以某个字符串 X 结尾并包含某个字符串 Y 的字符串使用 RegExp 构造函数

[英]Regex in javascript using RegExp contructor for the strings that ends with some string X and contains some string Y

I got RE of strings that starts with some string X and contains some string Y which was我得到了以某个字符串 X 开头并包含一些字符串 Y 的字符串 RE

const startsWith = 't'
const contains = 'te'
const re = new RegExp(`(?=.*${contains})^${startsWith}`)
re.test('teacher') // Result = true

But when I try to change it to ends with X and contains Y like但是当我尝试将其更改为以 X 结尾并包含 Y 时

const endsWith = 'e'
const contains = 'te'
const re = new RegExp(`(?=.*${contains})${endsWith}\$`)
re.test('ate') // Result = false

I did not get the desired result我没有得到想要的结果

I need a regex which would give true when word like 'ate' contains 'te' and also ends with 'e', also gives true when word like 'steve' contains 'te' and ends with 'e'.我需要一个正则表达式,当'ate'这样的单词包含'te'并且以'e'结尾时,它会给出true,当'steve'这样的单词包含'te'并以'e'结尾时也会给出true。 Currently my endsWith regex giving false on both.目前我的 endsWith 正则表达式都给出了 false 。

The "endsWith" part is always at the end of the string. “endsWith”部分始终位于字符串的末尾。

The generated regex looks like this (?=.*te)e$ and when the lookahead succeeds asserting (non consuming) te , the position is still at the start of the string.生成的正则表达式看起来像这样(?=.*te)e$并且当前瞻成功断言(非消耗) te时, position 仍位于字符串的开头。

The next part of the pattern tries to match e at the end of the string, but the position did not move yet and it did not match at before it to get to the e at the end.模式的下一部分尝试匹配字符串末尾的e ,但是 position 还没有移动,并且at它之前没有匹配到最后的e

You might write the pattern using .* in between to get to the end of the string, and add an anchor ^ before the lookahead to perform the assertion only once.您可以在中间使用.*编写模式以到达字符串的末尾,并在前瞻之前添加一个锚^以仅执行一次断言。

Note that you can escape the \$ but you don't have to.请注意,您可以转义\$但您不必这样做。

 const endsWith = 'e' const contains = 'te' const re = new RegExp(`^(?=.*${contains}).*${endsWith}$`) console.log(re.test('ate'))

1st let's understand why the 1st one is working and why the 2nd one is not working.第一个让我们了解为什么第一个工作以及为什么第二个不工作。

Example First:先例:

const startsWith = 't'
const contains = 'te'
const re = new RegExp(`(?=.*${contains})^${startsWith}`)
re.test('teacher') // Result = true

Debug:调试:

(?=.*te)^t (?=.*te)^t

Explain:解释:

Here (?=.*te) is "Positive lookahead", which means regex will start matching this and then will look ahead for the next conditions/rules.这里 (?=.*te) 是“积极的前瞻”,这意味着正则表达式将开始匹配它,然后将前瞻下一个条件/规则。

(
    ?=              Matches a group after the main expression (^t) without including it in the result.
    .               DOT, Matches any character except linebreaks
    *               Matches 0 or more of the preceding token
    t               Check for character 't'
    e               Check for character 'e'
)
^                   Matches the beginning of the string. This matches a position, not a character.
t                   Check for character 't'

Human Explain:人类解释:

Find every string which contains 'te' and ready to look after next rule which is find string which starts with 't'查找每个包含 'te' 的字符串,并准备好查找下一个规则,即查找以 't' 开头的字符串

Hence:因此:

teacher             //true, because it has 'te' and starts with 't'
thirdteacher        //true, because it has 'te' and starts with 't'
twoteacher          //true, because it has 'te' and starts with 't'
myteacher           //false, because it has 'te' but does not start with 't'

Example Second:示例二:

const endsWith = 'e'
const contains = 'te'
const re = new RegExp(`(?=.*${contains})${endsWith}\$`)
re.test('ate') // Result = false

Debug:调试:

(?=.*te)e$ (?=.*te)e$

Explain:解释:

Here (?=.*te) is "Positive lookahead", which means regex will start matching things after the main expression.这里 (?=.*te) 是“Positive lookahead”,这意味着正则表达式将在主表达式之后开始匹配内容。

(
    ?=              Matches a group after the main expression (e$) without including it in the result.
    .               DOT, Matches any character except linebreaks
    *               Matches 0 or more of the preceding token
    t               Check for character 't'
    e               Check for character 'e'
)
e                   Check for character 'e'
$                   Matches the end of the string. This matches a position, not a character.

Human Explain:人类解释:

Find every string which contains 'te' but as the main expression first find a string which ends as the last character 'e'.查找每个包含“te”的字符串,但作为主表达式,首先找到一个以最后一个字符“e”结尾的字符串。 it's end man.这是结束的人。 whoa.. yeah.. end.. end.. nothing after to match... it's ending.哇..是的..结束..结束..匹配后没有什么......它的结束。

  • Since... "Positive lookahead" failed here due to the main expression ends the search here using '$'由于...“正向前瞻”在此处失败,因为主表达式在此处使用“$”结束搜索

Hence "Positive lookahead" can not proceed for "lookahead"因此“前瞻”不能继续“前瞻”

Hence:因此:

regex will find... nothing, no match Ssshhhh... silence正则表达式会发现...什么都没有,不匹配 Ssshhhh...沉默

So what is the solution?那么解决方案是什么?

You have 2 options either use @The fourth bird solution which is ' (?=.*te).*e$ ' in debug mode.您有 2 个选项,要么在调试模式下使用@The Fourth Bird解决方案,即 ' (?=.*te).*e$ '。

Here '.这里 '。 ' is the main expression and gives "Positive lookahead" a chance to move and find strings and matches after. ' 是主要表达式,它让“Positive lookahead”有机会移动并在之后查找字符串和匹配项。 . .

(
    ?=              Matches a group after the main expression (e$) without including it in the result.
    .               DOT, Matches any character except linebreaks
    *               Matches 0 or more of the preceding token
    t               Check for character 't'
    e               Check for character 'e'
)
.                   DOT, Matches any character except linebreaks
*                   Matches 0 or more of the preceding token
e                   Check for character 'e'
$                   Matches the end of the string. This matches a position, not a character.

Human Explain:人类解释:

Hey!嘿! regex please bring me a string which contains 'te' and ends with 'e'正则表达式请给我一个包含'te'并以'e'结尾的字符串

Execution Pipeline for 'soulmate': “灵魂伴侣”的执行管道:

(?=.*te)            -- did you found 'te' yes 'solema*te*'
.*                  -- main expression is find everything, did you found, yes 'soulmate'
e$                  -- last expression is 'ends with e', did you find, yes 'soulmat*e*'

Master, here is the result - 'soulmate'师父,这是结果——“灵魂伴侣”

// false          tomato page
// false          yellow-teeth
// true           teeth-color-is-white
// true           ate
// false          future terminator
// false          AI is awful and should never be replaced with the human race.
// true           AI is good for telephones but awful for the human race
// true           I am running late
// true           e-gate
// true           soulmate
// false          time
// false          race
// false          ate-milan-cafes
// true           tell me the truth if mighty god is everywhere

Another option is using the native Javascript function.另一种选择是使用本机 Javascript function。 startsWith, includes and endsWith.开始,包括和结束。

Example:例子:

<script>
    var first = "teacher";
    var startwith = first.startsWith("t");
    var contains = first.includes("te");
    alert((contains && startwith)); // true
    var second = "ate";
    var contains = first.includes("te");
    var endwith = second.endsWith("e");
    alert((contains && endwith)); // true
</script>

-- Thank you - 谢谢

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

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