简体   繁体   English

如果字符匹配,则选择第N个字符-RegEx

[英]Select Nth character if the characters match - RegEx

I feel like an idiot which is not uncommon but I am working with RegEx and I need to select the 8th and 9th character if the characters match my input. 我觉得自己是一个白痴,这并不罕见,但是我正在使用RegEx,如果字符与我的输入匹配,则需要选择第8和第9个字符。 I have a working RegEx but it's not working with Javascript which I assume is due to the lookbehind? 我有一个可正常运行的RegEx,但是它不能与Javascript一起使用,我认为这是由于回溯?

What I have right now is the following: 我现在所拥有的是:

RegEx: 正则表达式:

(?<=^.{7})gg

This will match the 8th and 9th character if they contain 'gg'. 如果它们包含“ gg”,则将匹配第8个和第9个字符。

Any suggestions how I can get this working in Javascript? 有什么建议可以使我的Java语言正常工作吗?

Matching Groups solution 匹配组解决方案

^.{7}(gg)

Select the second group 选择第二组

var myString = "gsagq3eqsvertwfeqh3qfggsdfgsdh";
var myRegexp = /^.{7}(gg)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // Error
myString = "gsagq3eggvertwfeqh3qfggsdfgsdh";
myRegexp = /^.{7}(gg)/g;
match = myRegexp.exec(myString);
console.log(match[1]); // gg

Group Selection from: https://stackoverflow.com/a/432503/ 群组选择来自: https : //stackoverflow.com/a/432503/

This code returns: gg on the second match 这段代码在第二场比赛中返回:gg

Explanation 说明

^ Match the start of the string ^匹配字符串的开头

.{6} Match any first 6 chars .{6}匹配任何前6个字符

(gg) Match the desired string in a group (gg)匹配组中所需的字符串

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

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