0

I trying to use RegEx to capture the same word only when it appears alone (no compound) in a string that separates items with commas.

Example: Word,Word with Another,Word,ConcatWord

Match needed: "Word", "Word" - no comma

I have some limitations in the tool I'm using, so I can't use lookahead and lookbehind.

EDIT: It's not possible to select which match group I want to replace, the function can only see the full match.

This RegEx works but captures the comma in the full match: (Word)[^\s-]

Can someone help me?

7
  • You can replace the comma with whitespaces if u don't need comma then apply regrex on it. Jun 6, 2020 at 4:21
  • I use the comma to join the remaining elements after replace. Jun 6, 2020 at 4:23
  • I have checked ur input string and output on my system,it's capturing "Word" only. I used findall func.what is the problem ? Jun 6, 2020 at 4:49
  • The problem is the comma in the full match Jun 6, 2020 at 4:52
  • I don't understand what you mean by, "...I can't select which group in the match I want to extract,..". Please clarify by editing the question. Jun 6, 2020 at 4:58

2 Answers 2

1

As I understand we are given a string and the word "Word" and wish to return all instances of "Word" that are:

  • immediately preceded and followed by a comma;
  • are at the beginning of the string and are immediately followed by a comma;
  • are at the end of the string and are immediately preceded by a comma; or
  • the string is "Word".

You can match the following regular expression.

(?:^|,)(Word)(?:,|$)

Each instance of "Word" that matches is contained in capture group 1.

Demo

I would think obtaining matching instances of "Word" in the capture group would be of questionable use, as there would be no indication of which instances of "Word" in the string they referred to. Potentially more useful would be to save the indices in the string of instances of "Word" where there is a match. To do that, however, one must know which language that is being used.

1
  • Thank you, Cary! I can't select which group in the match I want to extract in this tool Jun 6, 2020 at 4:48
0

I added some regex patterns just try this. I used

  • Positive Lookahead (?=,)

  • Positive Lookbehind (?<=,)

  • word boundary (\b)

    /^\bWord(?=,)|(?<=,)\bWord(?=,)|(?<=,)\bWord$/gmi

1
  • Thank you! I can't use lookahead and lookbehind in this case. Not compatible with this tool Jun 6, 2020 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.