tags:

views:

986

answers:

4

I am try use

(?<key>.{5}keyword.{5}?)

to test "other string keyword other text"

it will get "ring keyword othe"

and I want "akeyword other text" or "other string keyworda" or "akeywordc" are match, too.

How to modify regex?


I have a long string and I want get find keyword and get it with perfix and suffix string

demands 5 just a sample it may change to any number like 50

my question is if the keyword's position less than 5 and it's not match.

how to get perfix or suffix string with keyword when perfix or suffix string length is

unknow.


Sorry, my question is not clear.

I want get get perfix or suffix string with keyword. and I want get prefix or sufiix string at most 5 word.

example:

"abcde keyword abcde" I want get "bcde keyword abcd"

and when prefix string less then 5 word

"a keyword abcde" I want get "a keyword abcd"

or suffix string less then 5 word

"abcd keyword a" I want get "abcd keyword a"

+1  A: 

It isn't clear what you want to pass and fail; in particular, the .{5} demands 5 characters before the keyword, so I'm not sure how "akeywordc" should match. The [\s\S]{5} says "5 white-space or non-whitespace"... so again, that demands 5 characters after (and could probably be .{5}).

So: how do you want it to behave?

For example, (?<key>.{1,5}keyword.{1,5}) will match 1-thru-5 characters before or after (greedily).

Marc Gravell
+1 for clear explanation
annakata
A: 

This could be as simple as (.*?)keyword(.*?) or it could be (.{0,5}) based as per Sebastiens answer, it still depends on what you mean by "unknown".

Do you mean that any number of matches would be acceptable, or only a specific number of matches but you don't know that number until runtime - in which case how do you know that number at runtime (we can't answer that for you).

It would still be best if you posted a set of matching sample strings and non-matching sample strings.


edit from OP update 2: then it seems you need a combination of mark and sebastiens answers

(?<key>.{0,5}keyword.{0,5})

that will include 0 to 5 chars of prefix and 0 to 5 chars of suffix with the match

annakata
+1  A: 

Could this be what you are looking for:

(?<key>.{0,5}keyword[\s\S]{0,5})
Sebastian Dietz
+1  A: 

This?

(?<key>.{0,5}keyword.{0,5})

You could use something like The Regulator to hack about while you learn how to solve this problem; teach a man to fish, and all that.