user1877031
user1877031

Reputation: 31

Ignoring hyphens deliberately

I am trying to write a small utility which can REPLACE some variables to some other format on around 8000 source code files.

For example, I have the following kind of source code written on Progress4GL. Note: Progress4GL allows to use hyphen in variable names:

where x-crudefn.segment-id[5] =crudefn.segment-id[v-idx]

I need to find exactly the occurance of crudefn.segment-id

When I use the regex (crudefn.segment-id)(\[), it finds it on both parts of equal sign.

In this case, x-crudefn.segment-id is another variable, which I DON'T want to replace.

I only want to replace the variable crudefn.segment-id

When I try to ignore hyphen using the regex [^\-](crudefn.segment-id)(\[), it also includes the equal sign in the match result("=crudefn.segment-id["), which I don't want. In some cases the source code is like:

where x-crudefn.segment-id[5] =crudefn.segment-id[v-idx]

and in some other cases it's like this:

where x-crudefn.segment-id[5] = a + crudefn.segment-id[v-idx]

Upvotes: 1

Views: 283

Answers (2)

user557597
user557597

Reputation:

You should look up what constitutes a variable name.
Then construct a regex around it.

I.e. starts with a word, ends with a word, etc...

(?<![-\w])crudefn\.segment-id(?![-\w])

This way you don't have to worry about stupid word boundaries
and spurious punctuation.

https://regex101.com/r/qQ6zZ8/4

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

It seems you want to match the crudefn word as a whole word but excluding the positions after a hyphen.

You can use

(?<!-)\bcrudefn\.segment-id\[

See the regex demo

The \b word boundary will make the word crudefn match after a non-word character, and the negative lookbehind (?<!-) will fail the match if a hyphen appears right in front of this word.

Also, note that a dot must be escaped to match a literal dot (otherwise, it will match any character but a newline.)

In Java,

String pattern = "(?<!-)\\bcrudefn\\.segment-id\\[";

Upvotes: 1

Related Questions