正则表达式 - 匹配Javascript中给定开头和结尾部分的文本部分

时间:2017-09-13 15:42:52

标签: javascript regex

我需要修剪一个可以在时间内改变的非常长的字符串。因为它是html我可以使用标签和属性名称来剪切它,无论内容如何。不幸的是我找不到写正则表达式匹配的方法。给出以下示例:

  

这是(随机字符)一个例子(随机字符)

我如何匹配(随机字符)和“这是”使用其余的,这总是相同的?我尝试过以下几点:

^(This is)((.|\s)*an)$
This is^(?!.*(an))

但一切似乎都失败了。我认为“beetween”中的“任何字符或空格”使搜索直接到字符串的末尾,我错过了“an”部分,但我无法弄清楚如何为此添加例外。 / p>

2 个答案:

答案 0 :(得分:0)

我不知道javascript,但我会假设以下函数,我将以某种形式存在一些松散的类似C的代码:

string input = "This is (random characters) an example (random characters)";

string pattern = "(^This is .*) an example (.*$)";
RegexMatch match = Regex.Match( str, pattern );

string group0 = match.GetGroup(0);//this should contain the whole input
string group1 = match.GetGroup(1);//this should get the first part: This is (random characters)
string group2 = match.GetGroup(2);//this should get the second part: (random characters) at the end of the input string

注意:通常在正则表达式中,括号会创建捕获组。

答案 1 :(得分:0)

'看后面'会对此有好处,但不幸的是,JS不支持它。但是,您可以使用RegExp和捕获组来获得所需的结果。

let matchedGroups = new RegExp(/^This is (.+) an example (.+).$/,'g')

matchGroups.exec('This is (random characters) an example (random characters).')

这将返回一个数组:

0:"This is (random characters) an example (random characters)."
1:"(random characters)" 
2:"(random characters)"

正如你所看到的那样,这有点笨重,但会给你两个可以使用的字符串。

相关问题