2014-07-13 2 views
-1

많은 사람들이이 질문에 혼란스러워 보였으므로 내가 할 수있는 한 간단하게 수행하고 싶은 것을 이야기하겠습니다.여러 용어 중 하나와 일치하는 자바 스크립트 정규식

"mak", "mind"및 "mass"로 시작하고 추가 또는 "e"또는 "er"로 끝나는 단어의 텍스트 문자열을 검색하려고합니다. 그것은 "mak", "make", "maker", "mind", "minde", "minder", "mass", "masse", "masser"입니다.

특정 문자로 시작하고 특정 문자로 끝나는 텍스트의 특정 단어를 찾으려고합니다. 다음 정규 표현식을 사용하고 있습니다.

aray = ['mak','mind', 'mass']; 
for(i=0; i < aray.length; i++){ 
    searchTerm = new RegExp(
     "\\b" + aray[i] + "\\b|" + 
     "\\b" + aray[i] + "en\\b|" + 
     "\\b" + aray[i] + "er\\b"); 
    word = testText.match(searchTerm, "gi"); 
} 

첫 번째 인스턴스가 일치하면 다른 인스턴스는 검색되지 않습니다. 누군가가 올바른 방향으로 나를 가리킬 수 있습니까? 어떤 도움이라도 대단히 감사하겠습니다.

이 질문은 중복으로 표시되었지만 다른 질문은 내가 어려움을 겪고있는 점에 대답하지 않습니다.

+0

주 일부 샘플 입력. – Braj

+0

이 주제를보아야합니다 : http://stackoverflow.com/questions/15090829/javascript-regex-pattern-match-multiple-strings-and-or-against-single-strin –

+2

gi " 잘못된 기능에 플래그; RegExp 생성자에 있어야합니다. 그 외에도, 당신이 여기서'word' * 내부 * 루프를 사용하는 한 특별한 문제는 보이지 않습니다. (루프 밖에서는 항상 마지막 일치가 무엇이든간에) – Dave

답변

0

searchTerm = new RegExp(...);을 할 때마다 정규 표현식을 다시 작성하므로 루프 내에서 표현식을 사용하지 않는 한 마지막 단어와 만 일치합니다.하지만 보이지는 않습니다. 그것. 나는 여전히 당신이 원하는 것을 추측하고 있지만 모든 단어와 일치하는 하나의 정규 표현식을 구성하려면 |과 결합 된 하나의 표현식에 모든 단어를 넣어야합니다.

또한 gi과 같은 플래그는 match 메서드가 아닌 RegExp 생성자에 전달되어야합니다.

var array = ['mak', 'mind', 'mass']; 
var searchTerm = new RegExp('\\b(' + array.join('|') + ')(e|er)?\\b', 'gi'); 
var match = testText.match(searchTerm); 
0
searchTerm = new RegExp("\\b(?:" + aray[i] + ")(?:er|e)?\\b"); 
The Regex is: \b(?:mak)(?:er|e)?\b 
It consists of: 
\b... Word Boundary 
Two non-capturing groups (?:) ==> Basically a group which cannot be addressed inside the regex. 
The first non-capturing group matches the beginning of the word. (?:mak) ==> mak is a placeholder for an entry of the array. 
The second non-capturing group matches the ending of the word. (?:er|e)? 
    The pipe character is an OR. 
    So this part matches er or e. 
    It is necessary to write er before e ==> if switched the regex engine would not find words ending with er. 
    The ? at the end means find zero or exact one times and enables finding the beginning without an (er or e) too.
+0

설명해 주시겠습니까? – andrewdotnich

관련 문제