質問

I want to capture non-contiguous text from a string using a regular expression and I'm finding it extremely difficult. ( Couldn't make it work)

I have the following:

"John KC Mary V oranges."

KC and V are tags and they will always exist in my strings. I want to capture "John V oranges" in this case.

So what I want is to remove KC and everthing until V ( With the exception of V).

I can't figure out how to do that. I´m doing that on a Java code, so I think I have some syntax limitations for regular expressions.

And another limitation is that I need to do that only using regular expressions. I can't use java replace.

If you guys could give me some ideas I will really aprecciate.

Thank you.

役に立ちましたか?

解決

you can use following regex

([a-zA-Z ]+)KC [a-zA-Z]+ (V [a-zA-Z]+)

Which will return an array like

Array
(
   [0] => John KC Mary V oranges.
   [1] => John
   [2] =>  V oranges.
)

and you can pick the last 2 indexes.. Simple ..

他のヒント

Use this regex for the search replace:

KC.*?\s(?=V)

It means anything after KC followed by V. And considering there is a space before the V.

Above regex is when you want to do search replace. But if you want to do it using regex match then the regex will be:

(.*?)\sKC.+(\sV.*)

After performing the regex match, just concat the group-1 and group-2 of the returned match.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top