Reputation:
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"
Upvotes: 1
Views: 2165
Reputation: 75872
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
Upvotes: 0
Reputation: 1110
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.
Upvotes: 1
Reputation: 1064124
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).
Upvotes: 1
Reputation: 5706
Could this be what you are looking for:
(?<key>.{0,5}keyword[\s\S]{0,5})
Upvotes: 2