如何使正则表达式变成非贪婪的? [英] How to make Regular expression into non-greedy?

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

问题描述

我正在使用 jQuery.我有一个带有特殊字符块(开始和结束)的字符串.我想从那个特殊字符块中获取文本.我使用正则表达式对象进行字符串内查找.但是,当有两个或更多特殊字符时,如何告诉 jQuery 查找多个结果?

我的 HTML:

<div id="文本容器">Cuộc简PHAPLýgiữa[|公司星期四|nghiệm|] THI张庭[|测试2 |đâyLà测试LAN 2 |]涌khoán[|我|天啦努尔卡我|] VA颜亨đầu涂quyền吕克山一河粉墙MOI驰bắt đầu.

和我的 JavaScript 代码:

$(document).ready(function() {var takedata = $("#textcontainer").text();var test = 'abcd adddb';var filterdata = takedata.match(/([.+])/);警报(过滤数据);//结束写js});

我的结果是:[|cơ thử|nghiệm|] thị trường [|test2|đây là test lần 2|] chứng khoán [|Mỹ|day la nuoc my|].但这不是我想要的结果:(.如何获得第 1 次的 [文本] 和第 2 次的 [演示]?

<小时>

我刚刚在网上搜索信息后完成了我的工作^^.我写这样的代码:

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

  • 我的结果是:[|cơ thử|nghiệm|],[|test2|đây là test lần 2|]这是对的!.但我真的不明白这一点.你能回答我的原因吗?

解决方案

非贪婪的正则表达式修饰符就像它们贪婪的对应部分,但紧随其后的是 ?:

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

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天全站免登陆