5

Suppose I have a String like following

@ABCD|NN12CT55|GFR

now I want to match

@ABCD|N

and replace it with

@ABCD N

regex for matching @ABCD\|[^G]

is there a way to remove the | from the capturing group?

4
  • 2
    @(TEST)\|\1 replace with @\1 \1 Commented Apr 6, 2017 at 11:49
  • @AvinashRaj its working for the given example, but i cant seem to adapt it into my needs. can you give me an solution for this? @ABCD|NN12CT55|GFR is input. and maybe a little explanation what it does? Commented Apr 6, 2017 at 11:53
  • Please update the question to show the real life scenario and explain what is wrong with your regex. You do not even have a capturing group in your regex, why do you ask how to remove a char from a capturing group? Perhaps, you need to use one. Like in (@ABCD)\|(?!G). Or (@ABCD)\|([^G]). Commented Apr 6, 2017 at 11:55
  • @WiktorStribiżew i know that i can repplace with $0 which matches the exact value from what the regex matches, but i dont want the | in it Commented Apr 6, 2017 at 12:06

1 Answer 1

5

You can try this regex

^@[^|]*\K\|

and replace by:

" "

Explanation:

  1. ^ marks start of a string
  2. @ matches @ sign
  3. [^|]* matches anything but not pipe |
  4. \K if match being found upto previous point, then \K makes the current position as starting point therefore the previous part wont be replaced
  5. \| matches the pipe --> this pipe is going to be replaced

Demo

Sign up to request clarification or add additional context in comments.

5 Comments

so \K always sets the new "start" of the match if it finds something which is not | and once the | occurs it stops resetting the start?
\K forgets about the past matches and marks the current position as match... as everything upto \K were to find everything but not | , therefore we need to forget about everything that we don't need to replace. \K does this. From there on the next character is | thus it gets matched. and all match thing is going to be replaced by " " i.e empty space
and how come it only matches the first pipe? is it because of ^?
let's first forget about \K, ^[^|]* means match everything which is not pipe from the initial point so it will match everything until |, as we know , thus I put a pipe | immediately to be matched and it get matched ... and i totally don't bother what comes after that matched | and don't even match anything
How can I use this with JavaScript API for Regular Expressions? I have watched your demo and it worked, but when I use it with JavaScript, then it always returns null! For example: var word = '@ABCD|NN12CT55|GFR'; let matchresult = word.match(/^@[^|]*\K\|/gm); console.log(matchresult) I tried exec, match, etc... but didnt work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.