正则表达式仅匹配字符串,而不是子字符串
当单击表中的值时,我将字符串添加到textarea。必须可以选择和取消选择表中的值,并且他们将自己从textarea中添加/删除自己。 textarea必须是一个字符串,并且添加的值不能包含在任何其他字符中。正则表达式仅匹配字符串,而不是子字符串
正在加入可以potentailly有任何字符,并且可具有其他的值作为子串中的一个的值,这里是一些例子:HOLE 1
,HOLE 11
,HOLE 17
,HOLE (1)
,cutaway
,cut
,away
, cut-away
,Commentator (SMITH, John)
,(GOAL)
,GOAL
一旦值已追加到textarea的,它的点击再次取消它,我在寻找的价值,像这样将其取出:
var regex = new RegExp("(?![ .,]|^)?(" + mySelectedText + ")(?=[., ]|$)", 'g');
var newDescriptionText = myTextAreaText.replace(regex, '');
正则表达式正确匹配文本的字符串/子字符串,例如然而,cutaway
和away
不适用于以括号开头的任何内容,例如(GOAL)
。将字边界选择器添加到表达式\b
的开头,将使正则表达式匹配以括号开头但不适用于包含相同文本的字符串/子字符串的字符串。
有没有办法实现这个使用正则表达式?或者其他一些方法?
这是一个正在运行的CodePen example的添加/删除表。
当您取消选择away
并在列表中有cutaway
时,可以使用字边界(\b
)来避免问题。只要改变正则表达式:
regex = new RegExp("(?![ .,]|^)?(\\b" + cellText + "\\b)(?=[., ]|$)", 'g');
^^^ ^^^
这是我改变,使它的工作原理代码:
removeFromDescription = function(cell) {
cell.classList.remove(activeClass);
// Remove from the active cells arry
var itemIndex = tempAnnotation.activeCells.indexOf(cell.textContent);
tempAnnotation.activeCells.splice(itemIndex, 1);
// Do the regex find/replace
var annotationBoxText = annotation.value,
cellText = regexEscape(cell.textContent), // Escape any funky characters from the string
regex = new RegExp("(^|)" + cellText + "(|$)", 'g');
var newDescription = annotationBoxText.replace(regex, ' ');
setAnnotationBoxValue(newDescription);
console.info('cellText: ', cellText);
console.info('annotationBoxText:', annotationBoxText);
console.info('newDescription: ', newDescription);
};
regexEscape = function(s) {
return s.replace(/([-\/\\^$*+?.()|[\]{}])/g, `\\$&`);
};
setAnnotationBoxValue = function(newValue) {
annotation.value = newValue;
};
您正确的做法是使正确匹配子字符串,但是如果'cellText =(GOAL)'即以括号开头,这将不匹配 –
@JoeHastings请参阅编辑:) –
完美!非常感谢 –
你要对这个错误的方式。为什么不将选定的值保存在'array'中,并根据值更改时刷新'textarea'的内容? – Sebastian
我也在想这个,但用户也可以在框中输入,例如“看看HOLE 1'现在看看'HOLE 11' blah blah',但通过键入他们可以点击'HOLE 1'并将其删除,尽管再次考虑它,我可能会存储一组对象包含字符串本身以及它在textarea中的当前开始位置 –