2

How do I fix this regex, to not touch the expansions like HYDRAULIC and only convert HYD and HYD. to HYDRAULIC and fix the space issue (for HYD.CYLINDER)?

Link of regex

Regex (hyd. and hyd):

\b(hyd)(?:\s|$|[^\w])

Test String:

HYD. CYLINDER
HYD CYLINDER
HYD.CYLINDER
HYDRAULIC CYLINDER
CYLINDER,HYD.
CYLINDER,HYDRAULIC
CYLINDER,HYD
CYLINDER, HYD.
CYLINDER, HYDRAULIC
CYLINDER,HYD

Substition:

HYDRAULIC

HYDRAULIC CYLINDER
HYDRAULICCYLINDER
HYDRAULICCYLINDER
HYDRAULIC CYLINDER
CYLINDER,HYDRAULIC
CYLINDER,HYDRAULIC
CYLINDER,HYDRAULICCYLINDER, HYDRAULIC
CYLINDER, HYDRAULIC
CYLINDER,HYDRAULIC
Isak La Fleur
  • 3,632
  • 6
  • 27
  • 41

3 Answers3

1

You may use

s = s.replace(/\bhyd(?:\.|\b)([a-z0-9]?)/gi, function($0, $1) { 
    return "HYDRAULIC" + ($1 ? " " + $1 : "") ; 
})

See the regex demo.

Regex details

  • \b - leading word boundary
  • hyd - a substring
  • (?:\.|\b) - a dot or word boundary
  • ([a-z0-9]?) - Capturing group 1: an optional alphanumeric char.

If Group 1 matches, the match is replaced with HYDRAULIC + space + the letter captured in Group 1, else, it is replaced with just HYDRAULIC.

Note that \bhyd(?:\.|\b) and \bhyd\b\.? suggested by The fourth bird are synonymous.

JS demo:

var strs = ['HYD. CYLINDER','HYD CYLINDER','HYD.CYLINDER','HYDRAULIC CYLINDER','CYLINDER,HYD.','CYLINDER,HYDRAULIC','CYLINDER,HYD','CYLINDER, HYD.','CYLINDER, HYDRAULIC','CYLINDER,HYD'];
var rx = /\bhyd(?:\.|\b)([a-z0-9]?)/gi;
for (var s of strs) {
  console.log(s, "=>", s.replace(rx, function($0, $1) { 
    return "HYDRAULIC" + ($1 ? " " + $1 : "") ; 
  }))
}
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • /\bhyd(?:\.|\b)([a-z0-9]?)/gi; how do I include an variable instead of a string "hyd" in the regex? – Isak La Fleur Apr 02 '19 at 10:00
  • 1
    @IsakLaFleur `var rx = new RegExp("\\b" + term + "(?:\\.|\\b)([a-z0-9]?)", "gi")`, it is a [commonly asked question](https://stackoverflow.com/questions/494035) on SO. If your term can contain special chars, ["escape" the term](https://stackoverflow.com/questions/3561493), `term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')`. If the term can start / end with special chars, you cannot rely on `\b`. – Wiktor Stribiżew Apr 02 '19 at 10:08
0

One way: probably not the best is to use this regex:

\b(hyd\.?)(?:\s|$|[^\w])

and sub with "HYDRAULIC " with space at the end

0

Just use this pattern: \b(hyd)\W+

Only new is \W+ - matches one or more non-word characters.

Then substitute it with HYDRAULIC (note space at the end!).

Demo

Michał Turczyn
  • 28,428
  • 14
  • 36
  • 58