Return separate characters in the same result

Asked

Viewed 36 times

0

It is possible to obtain in the same match (preferably the last) two characters that are in different positions within the string?

For example:

"xxxxto12b" -> "ab"

"xyxyxyyxxxxxc23d" -> "cd"

I know where the characters are relative to the end of the string. Using regex /(.)..(.)$/ get the two separate. I would like to return them in the same result.

  • Using only regex I’m not seeing how to capture only parts... you can explain in what context you’ll need it?

  • @Sergio needs a generic way to extract a substring from a string, depending on the application’s settings. It may be the last character, some in the middle, or in this case, a combination of a character in the middle and end. Using regex would only be possible to change the applied regex, keeping the rest of the execution flow equal.

  • 1

    In what language will you treat this string?

  • @Sergio Javascript

  • Do you think this works for you? -> https://jsfiddle.net/hesLqfoL/

  • I think the solution is to make a Join of the captured groups, from the second, more or less like you did. So it would work for /(.)..(.)$/, /(.)$/ and others. Thank you.

  • 1

    Put an answer with this idea, it can be useful to others.

Show 2 more comments

1 answer

0


Apparently it is not possible to return the same result. In my case the solution is to concatenate the pouch from the second. This way it works for a regex that returns 1, 2 or more results.

For example of the question (in JS):

r = /(.)..(.)$/;
s1 = "xxxxa12b";
m = r.exec(a); // ["a12b", "a", "b"]
s2 = m.slice(1).join(""); // "ab"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.