0

How do I create a regular expression to match subword which start with same prefix, for example aaa, the random word after that has random length.

aaa[randomword1]aaa[randomword2]

If I use pattern

(aaa\w+)*

it match (aaa) and [randomword1]aaa[randomword2]. But I want to match groups: aaa, randomword1, aaa, randomword2.

EDIT: I mean in the string may have multi times aaa, and I need match all subword aaa_randomword_times_n.

GAVD
  • 1,977
  • 3
  • 22
  • 40
  • You want a [non-greedy regex modifier](https://stackoverflow.com/questions/2824302/how-to-make-regular-expression-into-non-greedy/2824314#2824314) for your sub-word pattern, i.e. `\w+?` instead of `\w+` – Phu Ngo Oct 13 '17 at 04:11

2 Answers2

1

I suggest aaa(\w+)aaa(\w+), hope it will help you:)

Renshaw
  • 1,075
  • 6
  • 12
0

You can use following regular expression :

\b(aaa|(?<=\[).*?(?=\]))\b

\b..\b -> zero-width assertion word boundary to match word

aaa -> your specific word to look

| -> check for optional

(?<=[) look behind zero width assertion which checks characters after open square bracket([)

.*? : character to match

(?=])) => look ahead zero width assertion which matches characters before closing square bracket(])

Akash KC
  • 16,057
  • 6
  • 39
  • 59
  • Sorry but it not match, for example, `aaaSsdsaxczczaaaDsadasdaddxdsdfsdasaaaCvcxvcxv`. – GAVD Oct 13 '17 at 03:54
  • I've posted regex based on input given in your question and it's working fine for that. With the help of above approach, you can formulate your own regex to meet your requirement. – Akash KC Oct 13 '17 at 03:57