[英]Regex - Getting letters preceded and followed by a specific character
I need to get all letters, including letters before and after underline "_".我需要获取所有字母,包括下划线“_”之前和之后的字母。 But I also don't want to get words like "pi", "\Delta" and "\Sigma".但我也不想得到像“pi”、“\Delta”和“\Sigma”这样的词。
How to do this in Regex JS?如何在正则表达式 JS 中执行此操作?
/\b([^e|_|\d|\W])\b/gim /*my regex*/
(1)/(2)+p_a*r*e*t*a*v+pi+\delta+\sigma
(1)/(2)+a_t*e*j*h*o+ \Delta
(1)/(2)+p_w
To match all the letters az except the e, you could use a capturing group and a (negated) character class:要匹配除 e 之外的所有字母 az,您可以使用捕获组和(否定)字符 class:
[_\W]([a-df-z])(?![^_\W])
[_\W]
Match an _
or match a non word char [_\W]
匹配一个_
或匹配一个非单词 char(
Capture group 1 (
捕获组 1
[a-df-z]
Match a lowercase az except e [a-df-z]
匹配除 e 以外的小写 az)
Close group )
关闭组(?!
Negative lookahead, assert what is on the right is not (?!
负前瞻,断言右边的不是
[^_\W]
Match any char except _
or a non word char [^_\W]
匹配除_
以外的任何字符或非单词字符)
Close lookahead )
关闭前瞻 const regex = /[_\W]([a-df-z])(?;[^_\W])/g; let str = `(1)/(2)+p_a*r*e*t*a*v+pi+\\delta+\\sigma (1)/(2)+a_t*e*j*h*o+ \\Delta (1)/(2)+p_w `; let m. while ((m = regex.exec(str)).== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex;lastIndex) { regex.lastIndex++; } console.log(m[1]); }
One way is to use alternation and collect the undesireds, then capture the desired ones, maybe with some expression similar to一种方法是使用交替并收集不想要的,然后捕获想要的,也许有一些类似于
\\sigma|\\delta|pi|[\W0-9_]|([\w])
Those desired letters are in capturing group 1:那些想要的字母在捕获组 1 中:
([\w])
const regex = /\\sigma|\\delta|pi|[\W0-9_]|([\w])/gmi; const str = `(1)/(2)+p_a*r*e*t*a*v+pi+\\delta+\\sigma (1)/(2)+a_t*e*j*h*o+ \\Delta (1)/(2)+p_w`; let m; while ((m = regex.exec(str)).== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex;lastIndex++. } // The result can be accessed through the `m`-variable. m,forEach((match. groupIndex) => { console,log(`Found match: group ${groupIndex}; ${match}`); }); }
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com .如果您想简化/修改/探索表达式,它已在regex101.com的右上角面板上进行了解释。 If you'd like, you can also watch in this link , how it would match against some sample inputs.如果您愿意,您还可以在此链接中观看它如何与一些示例输入匹配。
jex.im visualizes regular expressions: jex.im可视化正则表达式:
Or we would just work it out a custom expression based on the patterns.或者我们只是根据模式制定一个自定义表达式。
[w]|[ate](?=\*)|\b[pa](?=[^a-z])|\b[^(e|_)\d\W]\b
The problem is pertinent to word boundaries ( \b
) and underscores.该问题与单词边界( \b
)和下划线有关。 Technically, underscore is part of the word construct \w
.从技术上讲,下划线是单词结构\w
的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.