简体   繁体   English

regex-匹配在Javascript中给定的文本开头和结尾部分

[英]regex - Match a portion of text given begin and end of the portion in Javascript

I need to trim a very long string that can change during time. 我需要修剪一个很长的字符串,该字符串会随时间变化。 Since it's html I can use tags and attributes name to cut it regardless of the content. 由于它是html,因此无论内容如何,​​我都可以使用标签和属性名称将其剪切。 unfortunately I can't find a way to write the regex match. 不幸的是,我找不到写正则表达式匹配的方法。 Given the following example: 给出以下示例:

This is (random characters) an example (random characters) 这是(随机字符)示例(随机字符)

How can I match the (random characters) and "This is" using the rest, which is always the same? 如何使用其余部分(总是相同)匹配(随机字符)和“这是”? I've tried something along the lines of the followings: 我已经尝试了以下方法:

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

but everything seems to fail. 但一切似乎都失败了。 I think that the "any character or space in beetween" part makes the search go right to the end of the string and I miss the "an" part, but I can't figure it out how to add an exception to that. 我认为“ beetween中的任何字符或空格”部分会使搜索直接到达字符串的末尾,而我却错过了“ an”部分,但是我无法弄清楚如何为此添加例外。

I don't know javascript, but I will assume the following functions I will write in some loosely C-like code exist in some form: 我不了解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

Note: Normally in Regular Expressions, The parentheses create capture groups. 注意:通常在正则表达式中,括号会创建捕获组。

'Look behind' would be good for this, but unfortunately, JS doesn't support it. 为此,“落后”将是一件好事,但是不幸的是,JS不支持它。 However, you can use a RegExp and capturing groups to get the result you want. 但是,您可以使用RegExp和捕获组来获取所需的结果。

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

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

This returns an array: 这将返回一个数组:

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

As you can see this is a little clunky, but will get you two strings that you can use. 如您所见,这有点笨拙,但是会为您提供两个可以使用的字符串。

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

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