Home > Back-end >  Scala Regex ReplaceAll: How to Replace All Groups?
Scala Regex ReplaceAll: How to Replace All Groups?

Time:06-10

The following regex replace works beautifully:

var line = "PRIMARY INDEX XPKDLRSRC_PMT_CLMPMT ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );"
println(line.replaceAll("""[UNIQUE\s]{0,1}PRIMARY INDEX [^\s]* \(""", "PRIMARY KEY ("))

It returns: PRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );

The point of the first group [UNIQUE\s] was to take care of the following as well

line = "UNIQUE PRIMARY INDEX XPKDLRSRC_PMT_CLMPMT ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );"
println(line.replaceAll("""[UNIQUE\s]{0,1}PRIMARY INDEX [^\s]* \(""", "PRIMARY KEY ("))

But the word UNIQUE does not get replaced and I end up with

UNIQUEPRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );

When I expected

PRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );

How to I get all groups in the regex replaced by a string?

CodePudding user response:

[UNIQUE\s] represents a single character consisting of any of the enclosed characters. For what you need, replacing it with (?:UNIQUE\s )? should do.

val line = "UNIQUE PRIMARY INDEX XPKDLRSRC_PMT_CLMPMT ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );"

line.replaceAll("""(?:UNIQUE\s )?PRIMARY INDEX [^\s]* \(""", "PRIMARY KEY (")
// res1: String = PRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );

(?:regex) represents a non-capturing group and appending the group with a ? makes it an optional match.

  • Related