如何使正规表达式成为非贪心? [英] How to make Regular expression into non-greedy?

查看:127
本文介绍了如何使正规表达式成为非贪心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery。我有一个字符串,带有一个特殊字符(开始和结束)。我想要从该特殊字符块获取文本。我使用正则表达式对象进行字符串查找。但是,如果有两个特殊字符或更多的字符,可以如何判断jQuery查找多个结果?



我的HTML:

 < div id =container> 
< div id =textcontainer>
库克·奇恩菲普·利giữa[|公司星期四|nghiệm|]thị·特鲁[|测试2 |đâyLà测试LAN 2 |]钟·科安[|我|天啦努尔卡我|] VA颜亨đầu图·奎燕埠吕克山一Phố墙mớichỉbắtđầu。
< / div>
< / div>

和我的JavaScript代码:

  $(document).ready(function(){
var takedata = $(#textcontainer)。text();
var test ='abcd adddb'
var filterdata = takedata.match(/(\ [。+ \])/);

alert(filterdata);

//结束写js
});

我的结果是: [|cơthử|nghiệm|]thịtrường[| test2 | đâllàtestlần2 |]chứngkhoán[|Mỹ| day la nuoc my |] 。但是这不是我想要的结果:(如何获得第一次和第二次的[demo]的文本?






我在互联网^^搜索信息后刚刚完成了我的工作,我制作了如下代码:

  var filterdata = takedata.match(/(\ [。*?\])/ g); 




  • 我的结果为:的 [| CO THU |nghiệm|],[| TEST2 |đâyLà测试LAN 2 |]
    这是对的,但!我真的不明白这个,你能回答我为什么吗?


解决方案

贪心的正则表达式修饰符就像他们的贪心的对手,但是紧跟着他们的

 code> *  - 零个或多个
*? - 零个或多个(非贪心)
+ - 一个或多个
+? - 一个或多个(非贪心)
? - 零或一
?? - 零或一(非贪婪)


I'm using jQuery. I have a string with a block of special characters (begin and end). I want get the text from that special characters block. I used a regular expression object for in-string finding. But how can I tell jQuery to find multiple results when have two special character or more?

My HTML:

<div id="container">
    <div id="textcontainer">
     Cuộc chiến pháp lý giữa [|cơ thử|nghiệm|] thị trường [|test2|đây là test lần 2|] chứng khoán [|Mỹ|day la nuoc my|] và ngân hàng đầu tư quyền lực nhất Phố Wall mới chỉ bắt đầu.
    </div>
</div>

and my JavaScript code:

$(document).ready(function() {
  var takedata = $("#textcontainer").text();
  var test = 'abcd adddb';
  var filterdata = takedata.match(/(\[.+\])/);

  alert(filterdata); 

  //end write js 
});

My result is: [|cơ thử|nghiệm|] thị trường [|test2|đây là test lần 2|] chứng khoán [|Mỹ|day la nuoc my|] . But this isn't the result I want :(. How to get [text] for times 1 and [demo] for times 2 ?


I've just done my work after searching info on internet ^^. I make code like this:

var filterdata = takedata.match(/(\[.*?\])/g);

  • my result is : [|cơ thử|nghiệm|],[|test2|đây là test lần 2|] this is right!. but I don't really understand this. Can you answer my why?

解决方案

The non-greedy regex modifiers are like their greedy counter-parts but with a ? immediately following them:

*  - zero or more
*? - zero or more (non-greedy)
+  - one or more
+? - one or more (non-greedy)
?  - zero or one
?? - zero or one (non-greedy)

这篇关于如何使正规表达式成为非贪心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆