Tomasz
Tomasz

Reputation: 610

replace pattern in a string (if exists)

i would like to remove a pattern from a string (if the pattern occurs). It looks like: "_20180301_010000_c", where numbers indicates the timestamp and 'c' is additional identifier.

Example:

 val text: String = "file-client-and-reports_20190512_010012_c.csv"
 val text2 = text.replaceAll("[0-9]","").replaceAll("___c","")
 // incr_claim-party-contact-number___c.dat - result after first replaceAll
 // incr_claim-party-contact-number.dat - result after second replaceAll - ok!

I used replaceAll method twice, but looking for the general rule.

Upvotes: 1

Views: 301

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

You may use

(?:_[0-9]+)+_c(?=\.[^.]+$)

Or, if there can be no _<digits> before _c use this variation:

(?:_[0-9]+)*_c(?=\.[^.]+$)

See the regex demo and the regex graph:

enter image description here

Details

  • (?:_[0-9]+)+ - one or more repetitions of a _ and 1+ digits sequence (if there can be no _<digits> before _c, replace the last + with * to match 0 or more repetitions)
  • _c - a _c substring
  • (?=\.[^.]+$) - that is immediately followed with . and 1+ chars other than . to the end of the string

Scala:

val text: String = "file-client-and-reports_20190512_010012_c.csv"
val text2 = text.replaceAll("""(?:_[0-9]+)+_c(?=\.[^.]+$)""","")
println(text2)
// => file-client-and-reports.csv

See online demo

Upvotes: 4

Related Questions