简体   繁体   English

Javascript从字符串中提取正则表达式

[英]Javascript extract regular expression from string

I've tried a few ways of doing this and I can't figure out why my .match always returns null. 我尝试了几种方法,我无法弄清楚为什么我的.match总是返回null。 Given the string below how can I extract the 04-Jun-2017 into it's own variable? 鉴于以下字符串,我如何将2017年6月4日提取到自己的变量中?

var str = "I need the only the    date 04-Jun-2017\n"

str.replace(/\n/g,' ');
var date = str.match(/^[01][0-9]-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$/);
alert(date)

First of all, str.replace(/\\n/g,' '); 首先, str.replace(/\\n/g,' '); does not modify str var since strings are immutable. 不修改str var,因为字符串是不可变的。 Then, you do not need the anchors ^ and $ , as the date is inside the string, it is not equal to the string itself. 然后,您不需要锚点^$ ,因为日期在字符串内部,它不等于字符串本身。 Also, you need to match days from 1 to 31 , but [01][0-9] only matches from 00 to 19 . 此外,您需要匹配从131天数,但[01][0-9]仅匹配从0019

You may consider using 你可以考虑使用

 var str = "I need the only the date 04-Jun-2017\\n" var date = str.match(/\\b\\d{1,2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{4}\\b/i); if (date) { console.log(date[0]); } 

The anchors are replaced with word boundaries \\b and the day part is changed into \\d{1,2} matching any 1 or 2 digits. 锚点用字边界\\b替换,日期部分更改为\\d{1,2}匹配任何1或2位数。 The i modifier will make the pattern case insensitive. i修饰符将使模式不敏感。

At first you should be more clear about your question. 首先,你应该更清楚你的问题。 Second here's what may be the answer 第二,这可能就是答案

var str = "I need the only the    date 04-Jun-2017\n"
var result  = str.replace('I need the only the    ','');
alert(result);

See how the .replace(valueToSearch,valueToReplace) function needs two parameters, first is the text to replace, so what ever you put inside it will search for inside the string, the second parameter is the value that it will replace it with, so in case you want to get rid of it just place an empty string. 看看.replace(valueToSearch,valueToReplace)函数如何需要两个参数,首先是要替换的文本,所以你放入其中的内容将在字符串内搜索,第二个参数是它将替换它的值,所以如果你想摆脱它只是放一个空字符串。

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

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