简体   繁体   中英

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. 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.

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:

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. However, you can use a RegExp and capturing groups to get the result you want.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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