4

我有以下名为 cityList 的数据数组:

 var cityList = [

     "Anaa, French Polynesia (AAA)",
     "Arrabury, Australia (AAB)",
     "Al Arish, Egypt (AAC)",
     "Ad-Dabbah, Sudan (AAD)",
     "Annaba, Algeria (AAE)",
     "Apalachicola, United States (AAF)",
     "Arapoti, Brazil (AAG)",
     "Aachen, Germany (AAH)",
     "Arraias, Brazil (AAI)",
     "Awaradam, Suriname (AAJ)",
     "Aranuka, Kiribati (AAK)",
     "Aalborg, Denmark (AAL)"
 ];

我想首先搜索从字符串开头开始的城市名称。

接下来我要搜索字符串的代码部分:AAA、AAB、AAC 等...

我想将搜索模式应用为 javascript 正则表达式,首先应用到城市名称,然后应用到城市代码。

这是我的正则表达式:

 //  this regular expression used for search city name
 var matcher = new RegExp("^" + re, "i");

 //  this regular expression used for search city code
 var matcher = new RegExp("([(*)])" + re, "i");

如何将这两个正则表达式组合成一个按描述工作的正则表达式?

4

6 回答 6

2

我建议这样做:

var myregexp = /^([^,]+),[^(]*\(([^()]+)\)/;
var match = myregexp.exec(subject);
if (match != null) {
    city = match[1];
    code = match[2];
} 

解释:

^        # Start of string
(        # Match and capture (group number 1):
 [^,]+   # One or more characters except comma (alternatively insert city name)
)        # End of group 1
,        # Match a comma
[^(]*    # Match any number of characters except an opening parenthesis
\(       # Match an opening parenthesis
(        # Match and capture (group number 2):
 [^()]+  # One or more characters except parentheses (alt. insert city code)
)        # End of group 2
\)       # Match a closing parenthesis

这假设任何城市名称都不会包含逗号(否则此正则表达式只会捕获逗号之前的部分),因此如果可能的话,您需要检查您的数据。我想不出一个例子,但这并没有说明什么:)

于 2012-10-10T06:09:41.553 回答
1

在这里,我建议采用完全不同的方法(ECMA-262 标准)。

由于使用正则表达式无论如何都需要线性搜索,如果您可以预处理数据,则可以设置一个城市对象数组:

function City(name, country, code){
  this.cityName = name;
  this.cityCountry = country;
  this.cityCode = code;
}

var cities = [];
cities.push(new City('Anaa', 'French Polynesia', 'AAA'));
// ... push the other cities

和一个搜索功能:

function GetCity(cityToSearch, cities){
  var res = null;
  for(i=0;i<cities.length;i++){
    if(cities[i].city = cityToSearch
      res = cities[i]; 
  }
  return res;
}

在运行时:

var codeFound = '';
var cityFound = GetCity('Arraias');
if(cityFound != null)
  codeFound = cityFound.cityCode;

评论

在这两种情况下,如果你要用世界上所有的城市来填充城市数组,城市名称不是关键!例如,美国有六个“斯普林菲尔德”。在这种情况下,更好的方法是使用双字段键。

于 2012-10-10T08:22:29.783 回答
1

这是我能做到的最优雅的方式:

var cityList = ["Anaa, French Polynesia (AAA)","Arrabury, Australia (AAB)","Al Arish, Egypt (AAC)","Ad-Dabbah, Sudan (AAD)","Annaba, Algeria (AAE)","Apalachicola, United States (AAF)","Arapoti, Brazil (AAG)","Aachen, Germany (AAH)","Arraias, Brazil (AAI)","Awaradam, Suriname (AAJ)","Aranuka, Kiribati (AAK)","Aalborg, Denmark (AAL)"];
var regex = /([a-z].+?),.+?\(([A-Z]{3,3})\)/gi, match, newList = [];

while (match = regex.exec(cityList)) {
    newList.push(match[1]+" - "+match[2]);
}

alert(newList[7]);
// prints Aachen - AAH

如果你不明白如何在你的正则表达式中使用括号,我建议你查看我从中学到的网站:http ://www.regular-expressions.info/

于 2012-10-10T07:35:02.423 回答
1
$("#leavingCity").autocomplete({ 
source: function(req, responseFn) {
            var re = $.ui.autocomplete.escapeRegex(req.term);
            var matcher = new RegExp("/^([^,]+),[^(]*\(([^()]+)\)/", "g"); 
            var a = $.grep(cityList, function(item,index) { return matcher.test(item); }); 
            responseFn(a); 
} });

试试这个,Tim Pietzcker 的常规表达

于 2012-10-10T06:30:36.683 回答
0

我想你想通过几个简单的步骤来完成这个:

  1. 在第一个括号之前和之后拆分数组中的每个字符串

  2. 将您的第一个正则表达式应用于字符串的第一部分。将结果存储为布尔变量,可能命名为matchOne

  3. 将第二个正则表达式应用于字符串的第二部分(不要忘记删除右括号)。将结果存储为布尔变量,可能命名为matchTwo

  4. 测试两个数学中的任何一个是否成功:return ( matchOne || matchTwo );

于 2012-10-10T06:26:46.430 回答
0

使用 indexOf

它更有效,更明确的期望。正则表达式是不必要的。

const isMatchX = cityList.indexOf('AAB');
const isMatchY = cityList.indexOf('Awar');

或者,您可以这样做,但是当您可以使用 indexOf 时,它的方式过大:

const search = (cityList, re) => {
  const strRegPart1 = "¬[^¬]*" + re + "[^¬]*";
  const strRegPart2 = "¬[^¬]*\\([^\\)]*" + re + "[^\\)]*\\)($|¬)";
  const regSearch = RegExp("(" + strRegPart1 + "|" + strRegPart2 + ")", "gi");
  const strCityListMarked = '¬' + cityList.join('¬');
  const arrMatch = strCityListMarked.match(regSearch);
  return arrMatch && arrMatch[1].substr(1);
}
于 2020-09-10T15:13:33.180 回答