简体   繁体   English

正则表达式从长字符串中提取两个项目

[英]regular expression to extract two items from a long string

There are some strings having the following type of format, 有些字符串具有以下格式类型,

{abc=1234457, cde=3,  label=3352-4e9a-9022-1067ca63} <chve>  abc?  123.456.789, http=appl.com 

I would like to extract 1234457 and 3352-4e9a-9022-1067ca63 , which correspond to abc and label respectively. 我想提取分别对应于abclabel 12344573352-4e9a-9022-1067ca63

This is the javascript I have been trying to use, but it does not work. 这是我一直在尝试使用的javascript,但是它不起作用。 I think the regular expression part is wrong. 我认为正则表达式部分是错误的。

var headerPattern = new RegExp("\{abc=([\d]*),,label=(.*)(.*)");
if (headerPattern.test(row)) {
   abc = headerPattern.exec(row)[0];
    label = headerPattern.exec(row)[1];
}

Try: abc=(\\d*).*?label=([^}]*) 试试: abc=(\\d*).*?label=([^}]*)

Explanation 说明

  • abc= literal match abc=文字匹配
  • (\\d*) catch some numbers (\\d*)捕捉一些数字
  • .*? Lazy match 懒人比赛
  • label= literal match label=文字匹配
  • ([^}]*) catch all the things that aren't the closing brace ([^}]*)捕获所有不是右括号的东西

Here is what I came up with: 这是我想出的:

\{abc=(\d+).*label=(.+)\}.*

Your have two problems in \\{abc=([\\d]*),,label=(.*)(.*) : 您在\\{abc=([\\d]*),,label=(.*)(.*)有两个问题:

  • Using abc=([\\d]*),, , you are looking for abc=([\\d]*) followed by the literal ,, . 使用abc=([\\d]*),,寻找abc=([\\d]*)后跟文字 ,, You should use .* instead. 您应该改用.* Since .* is nongreedy be default, it will not match past the label . 由于.*不是默认值,因此它将不会超过label
  • By using label=(.*)(.*) , the first .* captures all the remaining text. 通过使用label=(.*)(.*) ,第一个.*捕获所有剩余的文本。 You want to only catch text until the edge of the braces, so use (.*)}.* . 您只希望捕获文本直到大括号的边缘,所以请使用(.*)}.*

Disclaimer: Made with a Java-based regex tester. 免责声明:使用基于Java的正则表达式测试器制作。 If anything in JavaScript regexes would invalidate this, feel free to comment. 如果JavaScript正则表达式中的任何内容会使它无效,请随时发表评论。

You can do it the following way: 您可以通过以下方式进行操作:

var row = '{abc=1234457, cde=3,  label=3352-4e9a-9022-1067ca63} <chve>  abc?  123.456.789, http=appl.com';

var headerPatternResult = /{abc=([0-9]+),.*?label=([a-z0-9\-]+)}/.exec(row);

if (headerPatternResult !== null) {
    var abc = headerPatternResult[1];
    var label = headerPatternResult[2];

    console.log('abc: ' + abc);
    console.log('label: ' + label);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM