Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex ignore middle part of capture

Tags:

c#

regex

I want a single regex that when applied to : "firstsecondthird" will match "firstthird" (in single group, ie in C# Match.Value will be equal to "firstthird").

Is that possible? we can ignore suffix or prefix , but middle?

like image 788
Valentin Kuzub Avatar asked Oct 14 '11 13:10

Valentin Kuzub


People also ask

What is\\ in regex?

To match a literal space, you'll need to escape it: "\\ " . This is a useful way of describing complex regular expressions: phone <- regex(" \\(? #

How to use end of string in regex?

End of String or Before Ending Newline: \Z The \Z anchor specifies that a match must occur at the end of the input string, or before \n at the end of the input string. It is identical to the $ anchor, except that \Z ignores the RegexOptions. Multiline option.

What does capture mean in regex?

capturing in regexps means indicating that you're interested not only in matching (which is finding strings of characters that match your regular expression), but you're also interested in using specific parts of the matched string later on.

How to start and end regex?

The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end. The pattern ^Mary means: “string start and then Mary”.


3 Answers

match a string that starts with 'first', has zero or more other characters, then ends with 'third'. Is that what you mean?

"^first(.*)third$"

Or, do you mean if you find a string 'firstsecondthird', ditch everything apart from 'first' and 'third'?

replace("^(first)second(third)$", "$1$2")
like image 125
duncan Avatar answered Nov 15 '22 23:11

duncan


No, there is no facility to make a single match group containing non-contiguous text from the target string. You will need to use replace, or glue together the matching groups into a new string.

like image 21
tripleee Avatar answered Nov 16 '22 00:11

tripleee


AFAIK, it is not possible to do with a single regular expression. You will have to use a call to replace(); as follows:

String inputVar = "firstsecondthird";
String resultVar = Regex.replace(inputVar, "^(first)second(third)$", "$1$2");

which can (typically...) be inserted into an expression as necessary

like image 43
Code Jockey Avatar answered Nov 15 '22 23:11

Code Jockey