-4

Hi I have a string for example aaaaabbbaaaababababaaaaabaaa. Now I want to be able to go to Nth place and if it is an "a" replace with "b" and if it is a "b" replace with an "a".

If this can´t be done with REGEX, what is the REGEX pattern to find and replace simply the Nth character with an "a".

Been trying to figure out REGEX but it´s more complex than German :(

Thanks

Chris
  • 1
  • 1
  • The regex are present in the code to prevent the user from typing anything wrong. For example an age does not have characters etc ... Here, it is not a regex but methods you need. – F0XS Nov 20 '17 at 11:00
  • You don't need `regex` to find, inspect and modify a character identified by its position inside the string. The programming language you use provides functions/methods to work with strings and that's all you need for this purpose. – axiac Nov 20 '17 at 11:01
  • Thing is i´m using bubble.is and it ONLY allows find-replace with regex. It´s a non-techie´s (codefree) website builder but allows REGEX, hence the need to use that. – Chris Nov 20 '17 at 11:04
  • @Chris Bubble is a visual programming language, the fact is that on `bubble.is` you can not type code. If the site you want to do needs more specificity, you use the wrong tool. Even if your only possibility is to manipulate the `REGEX` it does not change the fact that you can not handle the strings with. – F0XS Nov 20 '17 at 11:16
  • ok. But is there a way to do that in REGEX? How can i find the Nth character for example? – Chris Nov 20 '17 at 11:28
  • ok found out how to select the nth character: .(?<=^.{9}) would be awesome if i could find out how to replace though. – Chris Nov 20 '17 at 11:31
  • Regular expressions as such do not have any facility for modifying a string. They can match and (by extension) return the matched substring, but what happens then is completely under the control of the calling language. You might be able to pull something off with `^.{38}a` to match an `a` at an the 39th position in the string, but the rest will depend on the platform you are using. – tripleee Nov 20 '17 at 11:31
  • You don't understand.... `replace` is a method, it does not exist in `REGEX`. This is not a language, It is an abbreviation of regular expressions. Search in google for exemple you will understand. – F0XS Nov 20 '17 at 11:38

1 Answers1

0

Conditional replacement exists in some regex engine (at least Boost, used for example by Notepad++).

Assuming you want to toggle 10th character in your given input. Use this regex to find it (as you already managed to):

(?<=^.{9})(?:(a)|b)

Character occuring at that position will be stored in group 1 if an a, 2 if a b, else in group 3.
Using that conditional replacement pattern will toggle it if a or b are found, or else will let it unchanged:

?1b:a

You can test it in Notepad++ hitting "Replace all" button.

Note: another example of conditional replacement here.

PJProudhon
  • 835
  • 15
  • 17