复杂正则表达式组合 - 匹配“if”的正则表达式

时间:2013-10-03 02:01:09

标签: javascript regex

我正在使用正则表达式来匹配我的项目的主题标签。我想要由单个空格分隔的正则表达式匹配主题标签,在此内容中没有其他主题标签,只是匹配字符串中的空格(如果后跟任何单词)(其他空格除外)或#)。

我真的很想知道我是否可以在正则表达式中做“if”之类的事情,我希望你能帮助我。

所以,在:

"#hashtag?!-=_"  "#hashhash#"  "#hash tag"  "#hash  tag"  "#hash #ahuhuhhuasd" "#hash "

正则表达式必须与以下句子匹配:

"#hashtag?!-=_" "#hashhash" "#hash tag" "#hash" "#hash #ahuhuhhuasd" "#hash"
                            (all hashtag)        (one)  (another h.)

实际上,这是我的代码:

#{1,1}\S+\s{0,1}

您可以测试here此代码,但它会匹配不需要的内容:

"#ahusdhuas?!__??###hud #ahusdhuads "  
The blank space in the end of the string, the 3 '#' inside the string. 
none of the following content is desired in this string, just "#ahusdhuas?!__??"

很高兴你能帮助我!

5 个答案:

答案 0 :(得分:1)

尝试:

#[^# ]+(?: [^# ]+)*

匹配#,然后匹配一个或多个非#的字符,然后匹配0个或多个实例(一个空格后跟一个或多个不是'的字符' t #)。 ?:使该组无法捕获。

如果您根本不想与###hud中的#ahusdhuas?!__??###hud #ahusdhuads匹配,因为它以三个#开头,您可以在前面添加否定的lookbehind:(?<!#)正则表达式:

(?<!#)#[^# ]+(?: [^# ]+)*

然而,这将在Ruby中运行,但在JavaScript中不起作用,因为JavaScript没有能力执行lookbehinds。在这种情况下,您必须使用#[^# ]+(?: [^# ]+)*模式,如果匹配在第一个字符后面开始,请测试代码中字符串中的前一个字符,看它是否为#,并且如果是这样,拒绝正则表达式返回的匹配。

答案 1 :(得分:1)

这些都是你一直在寻找的吗?

enter image description here

enter image description here

答案 2 :(得分:1)

我认为这就是你所需要的:

(#(?:\s?[^#\s]+)+)

以下是一些测试:

enter image description here

答案 3 :(得分:1)

我想我明白了,虽然我不习惯Javascript的正则表达式,因为我只使用Python。
我在Monty Wild提供的网站regexpal.com上测试了以下内容,它是唯一一个向我显示所有匹配的子字符串:

(?:^ |^| )(#[^#\s]+(?: [^#\s]+)?)(?:(?=\Z| \Z| \S)| +(?=#))

结果

#hashtag?!-=_
#hash tag
#hash
#ahuhuhhuasd
#hash

由于Javascript的regexex不接受lookbehind断言,我使用了一个技巧,使得前面有两个或多个空格的hastag将不匹配:这些前面的空白被正则表达式机器消耗为前面匹配中的后续空白:这是正则表达式的最后一部分+(?=#)的作用,如果不止一个,则匹配matcjing的尾随空格。只有前一部分(?=\Z| \Z| \S)不匹配

时,此消耗才会介入

答案 4 :(得分:1)

在标准的HTML页面和Firebug中试过这个......

再次输入您提供的输入。

var hashTags = ["#hashtag?!-=_", "#hashhash#", "#hash tag", "#hash  tag", "#hash #ahuhuhhuasd", "#hash ", "#hash #", "#foo bar baz"];
hashTags.forEach(function(el, idx, arr) {
    console.log( el.match(/#([^#\s]|(( [^\s])(?!\s|$)))+/g));
});

// Console output
> ["#hashtag?!-=_"]
> ["#hashhash"]
> ["#hash tag"]
> ["#hash"]
> ["#hash #ahuhuhhuasd"]
> ["#hash"]
> ["#hash"]
> ["#foo bar baz"]