簡體   English   中英

正則表達式:匹配多個單詞的首字母

[英]Regex: Matching the first letter(s) of multiple words

所以我對正則表達式真的很不好...我現在用谷歌搜索了一個小時,我能找到的最好的答案是這個

但是我仍然無法為我解決...

我需要的是以下內容:

我有一個JS數組,我需要.filter() 該數組包含例如:

[ 'Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW' ]

例如: 以下所有輸入均應與第一個輸入匹配( "Gurken halbiert 2kg" ):

  • "Gu ha"
  • "gur h"
  • "gu halbi"

以下輸入不匹配它:

  • "ken halbi"
  • "urk ha"
  • "gur biert"

為什么? 因為缺少任何單詞開頭的一個或多個字母。

更多示例輸入及其應匹配的條目:

  • 輸入: "Gur" ->匹配第一個和第三個條目
  • 輸入: "Kar g 5" ->匹配第二
  • 輸入: "G r" ->匹配第3個

我真的希望有人能提供幫助,因為我在RegEx的混亂中完全迷失了-我從不真正了解它們或如何使用它們。

由於輸入有所不同,因此您需要動態生成正則表達式。

在下面的函數中,您會注意到我們基本上是在構建一個字符串,然后使用new RegExp(string, 'i')創建正則表達式。

表達式以尖號開始,然后基本上遵循以下模式:

^[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*

值得指出的是,在每個輸入字符串之后都添加了\\w*如果不是最后一個輸入字符串(即,不是結尾),則添加了\\s+

function generateRegex (input) {
  var string = '^', arr = input.trim().split(' ');
  arr.forEach(function (chars, i) {
    string += chars + '\\w*' + (arr.length - 1 > i ? '\\s+' : '');
  });

  return new RegExp(string, 'i');
}

然后,您可以在數組上使用.filter()方法並返回匹配的元素:

var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW'];
var filteredArray = array.filter(function (value) {
  return value.match(generateRegex('Gur Ha'));
});

輸出:

'Gur Ha'將匹配: ["Gurken halbiert 2kg"]

'Gur'將匹配: ["Gurken halbiert 2kg", "Gurken RW"]

'Kar g 5'將匹配: ["Karotten geschnitten 5kg"]

'G r'將匹配: ["Gurken RW"]


例:

 function generateRegex (input) { var string = '^', arr = input.trim().split(' '); arr.forEach(function (chars, i) { string += chars + '\\\\w*' + (arr.length - 1 > i ? '\\\\s+' : ''); }); return new RegExp(string, 'i'); } var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW']; var filteredArray = array.filter(function (value) { return value.match(generateRegex('Gur')); }); document.body.textContent = JSON.stringify(filteredArray); 

這是如何按指定過濾用戶輸入的示例。

筆記

  • 從用戶輸入模式轉義正則表達式字符(始終清除用戶輸入)。
  • 顯式不使用“ \\w ”來支持“ é ”之類的字符。
  • 支持<space>以外的空白字符,例如<tab> ,可以將其復制並粘貼到用戶輸入字段中,從而使用戶認為它已損壞。

 function doSubmit() { // Get the user input search pattern string var userInput = document.getElementById("myinput").value, // List of strings to search testList = [ 'Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW' ], // Between our "words" we allow zero or more non-space characters "[^\\s]*" // (this eats any extra characters the user might not have specified in their search pattern) // followed by one or more white-space characters "\\s+" // (eating that space between the "words") // Note that we are escaping the "\\" characters here. // Note we also don't use "\\w" as this doesn't allow for characters like "é". regexBetween = '[^\\\\s]*\\\\s+', // Match the start of the string "^" // Optionally allow one or more "words" at the start // (this eats a "word" followed by a space zero or more times). // Using an empty string here would allow "og" to match the 2nd item in our test array. regexStart = '^(?:' + regexBetween + ')*', // Clean whitespace at begining and end regexString = userInput.trim() // Escape any characters that might break a regular expression // Taken from: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions .replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&") // Split into array of "words" .split(/\\s+/) // Combine the "words" building our regular expression string .join(regexBetween), // Create the regular expression from the string (non-case-sensitive 'i') regexObject = new RegExp(regexStart + regexString, 'i'), // Filter the input array testing for matches against the regular expression. resultsList = testList.filter(function(item) { return regexObject.test(item); }); // Ouput the array into the results text area, one per line. document.getElementById('output').value = resultsList.join('\\n') + '\\n===the end==='; } 
 <form id="myform" onsubmit="doSubmit(); return false;"> <input type="text" id="myinput" value="" /> <input type="submit" name="submit" /> </form> <textarea id="output" rows="5" cols="30"> </textarea> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM