对样式的变化进行RegExp的最简单方法是什么?

时间:2018-08-01 16:33:07

标签: javascript regex function

我的代码(如下)在字符串中搜索可能包含dd[Q]dd[A], d[Q]d[A], dd[Z]dd[A], d[Z]d[A]的模式中的4种可能的变体。我的目标是始终找到字符Q和A(或Z和A)之间的数字并返回数字和索引位置。

我相信我的代码可以用更高效的方式编写,但是我不确定它是什么(我是初学者)。有什么想法吗?

{
var str = 'TY 111-222 4Q8A';
var result;
var index;
/*RegExp the 4 possible variations of the pattern*/
var srchAlpha = /\d\d\*?[Q]\d\d\*?[A]/i; 
var srchBeta = /\d\*?[Q]\d\*?[A]/i; 
var srchGamma = /\d\d\*?[Z]\d\d\*?[A]/i;
var srchDelta = /\d\*?[Z]\d\*?[A]/i;
/*Index the 4 possible variations of the pattern*/
var indexAlpha = str.search(srchAlpha);
var indexBeta = str.search(srchBeta);
var indexGamma = str.search(srchGamma);
var indexDelta = str.search(srchDelta);
/*Determine which variation of the pattern the string contains*/
if (indexAlpha != -1) {
result = str.slice(indexAlpha+3, indexAlpha+5);
index = indexAlpha+3;
} else if (indexBeta != -1) {
result = str.slice(indexBeta+2, indexBeta+3);
index = indexBeta+2;
} else if (indexGamma != -1) {
result = str.slice(indexGamma+3, indexGamma+5);
index = indexGamma+3;
} else if (indexDelta != -1) {
result = str.slice(indexDelta+2, indexDelta+3);
index = indexDelta+2;
} else {
result = "";
index = "";
}
document.getElementById("result").innerHTML = result;
document.getElementById("index").innerHTML = index;
}
<p>result: <span id="result"></span></p>
<p>index: <span id="index"></span></p>

2 个答案:

答案 0 :(得分:1)

如果字母之间可能没有数字,那么我相信[QZ](\d*)A可以。

如果期望至少一位数字,请输入[QZ](\d+)A

如果只有一位或两位数,请使用[QZ](\d{1,2})A

执行以下操作以提取数字和索引:

const regex = /[QZ](\d+)A/;
const input = "TY 111-222 4Q8A";

const match = input.match(regex);

if (!match)
  // no match

const digits = match[1];
const digitsIndexes = input.indexOf(digits);

对于两组数字(在QZ字符之前和之后),使用两个捕获组:

const regex = /(\d+)[QZ](\d+)A/;

// ...

const digitGroups = [ match[1], match[2] ];
const digitGroupsIndexes = digitGroups.map(group => input.indexOf(group));

答案 1 :(得分:0)

作为参考,根据德米特里·帕尔日斯基(Dmitry Parzhitsky)的回答,我在这里有完整的答案。

long numberofLines = 0;
try (Stream<String> stream = Files.lines(filePath)) {
        numberOfLines = stream.count();
} catch (IOException ex) {
    //catch exception
}
{
var regex = /(\d+)[QZ](\d+)A/;
var input = "TY 111-222 4Q8A";
var match = input.match(regex);

if (!match) {
digits = "";
digitsIndexes = "";
} else {
var digits = match[2];
var digitsIndexes = input.indexOf(digits);
}
document.getElementById("result").innerHTML = digits;
document.getElementById("index").innerHTML = digitsIndexes;
}