我得到了有数千行的excel,像这样:
Basic medical supply - AIT - needs documents from trasnport - drugs
Basic medical supply - TTT - needs documents from trasnport - patiens and other stuff
random string from excel - TTP - other text like always - marijuana per rectum如何将正则表达式设置为接受第三个"-“字符后的字符串。在这个例子中,“毒品”,“病人和其他东西”和“直肠的大麻”。
它不能做在jQuery等需要是纯JS,因为我是在五子棋BI脚本它。这个字符串将是非常随机的,只有3个“-”字符是常量。有可能做这样的事情吗?也许将所有内容都放到第三个“-”切片中,然后保存到变量中,然后删除空格和非字母字符?
编辑:
我刚刚注意到,在此列的文件中,每隔一行就有产品代码:
550-1008-000000-405.02.04.03我还必须在E.Q550-1028和405.02.04.03上对其进行拆分,因此我必须删除字符串中间的那些零,并获得2个子字符串
发布于 2016-11-23 20:54:49
正则表达式可以只是/^.+-.+-.+-\s*([^-]+)\s*$/
或者更简单:/-\s*([^-]+)\s*$/
最后一个"-“之后的所有内容。或者该字符串本身是否包含"-“?
发布于 2016-11-23 20:55:30
下面的正则表达式可以解决这个问题:
^([^-]+-){3}(.*)结果是用$2编写的,因此一个独立的代码片段将如下所示:
var s = [
'Basic medical supply - AIT - needs documents from trasnport - drugs'
, 'Basic medical supply - TTT - needs documents from trasnport - patiens and other stuff'
, 'random string from excel - TTP - other text like always - marijuana per rectum'
]
, res
, i;
for ( i=0; i < s.length; i++ ) {
res = s[i].replace(/^([^-]+-){3}(.*)/g, "$2");
console.log ( "#" + i + ": '" + s[i] + "# -> '" + res + "'\n" );
}正则表达式101上的live test。
说明
正则表达式基于除-之外的任意字符序列,后面跟一个-。它匹配此碱基序列的3个连续出现,并将该行的其余部分分配给捕获组2。
警告
注意连续的-字符-此解决方案与这些字符串不兼容,处理这些字符串的正确方法可能取决于您的数据(例如。--可以作为破折号—的ascii表示出现吗?)。
发布于 2016-11-23 20:54:40
如果你真的想要一个正则表达式,你可以使用这个:
var s = 'Basic medical supply - AIT - needs documents from trasnport - drugs';
var regex = /[^-]+-[^-]+-[^-]+-(.*)/;
var match = regex.exec(s);
console.log(match[1]); //outputs "drugs"但我更喜欢@VinodLouis (在评论中)的解决方案,而不是使用正则表达式……
https://stackoverflow.com/questions/40764859
复制相似问题