1

I want to convert some text to something else with replaceall and regular expressions.

My text is like the following:

This is with something extra constraint xhiho,

This is without something extra constraint hfdlh

Now what I want as result is the following:

This is with something extra, --constraint xhiho

This is without something extra -- constraint hfdlh

So I need to put 2 - before the word constraint and if there is a , at the end put it in front of the 2 -

I tried with the following piece of code:

oConvert = oConvert.replaceAll("constraint(.*)(,?)", "$2--constraint$1");

But it is not working, it does not give the , in front of the 2 -

anubhava
  • 761,203
  • 64
  • 569
  • 643
nightfox79
  • 2,077
  • 3
  • 27
  • 40

1 Answers1

2

You may use:

str = str.replaceAll("(\\h+constraint\\h+[^,]*)(,?)", "$2 --$1");

RegEx Demo

RegEx Details:

  • (: Start capture group #1
    • \h+: Match 1+ whitespaces
    • constraint: Match constraint
    • \h+: Match 1+ whitespaces
    • [^,]*: Match 0 or more of any characters that are not ,
  • ): End of capture group #1
  • (: Start of capture group #2
    • ,?: Match an optional comma
  • ): End of capture group #2
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This doesn't work, it doesn't put the , in front of the -- – nightfox79 May 15 '20 at 14:01
  • There will be a `,` before `--`. Did you check output in linked demo: https://regex101.com/r/jjHC5N/1/ – anubhava May 15 '20 at 14:03
  • Note that if trailing comma is not at then end then `$` will not be matched and you should use: `(\\h+constraint\\h+[^,]*)(,?)` as regex. – anubhava May 15 '20 at 14:06
  • After the comma are spaces, so the second option is better, but it also puts a , in front of the -- where it shouldn't be – nightfox79 May 15 '20 at 14:10
  • But you wanted to put `,` before `--` if there is a comma in the end. Can you check output in https://regex101.com/r/jjHC5N/2 and let me know if this is what you wanted. – anubhava May 15 '20 at 14:12
  • If I check on the website this works, but if I use it in my java program with replaceAll it does not. I did a copy paste of my code in the website and it worked. But in java with the same copy past it did not work – nightfox79 May 15 '20 at 14:17
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213938/discussion-between-anubhava-and-nightfox79). – anubhava May 15 '20 at 14:19