问题描述:

As a beginner with regex i believe im about to ask something too simple but ill ask anyway hope it won't bother you helping me..

Lets say i have a text like "hello 'cool1' word! 'cool2'"

and i want to get the first quote's text (which is 'cool1' without the ')

what should be my pattern? and when using matcher, how do i guarantee it will remain the first quote and not the second?

(please suggest a solution only with regex.. )

网友答案:

Use this regular expression:

'([^']*)'

Use as follows: (ideone)

Pattern pattern = Pattern.compile("'([^']*)'");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Or this if you know that there are no new-line characters in your quoted string:

'(.*?)'

when using matcher, how do i guarantee it will remain the first quote and not the second?

It will find the first quoted string first because it starts seaching from left to right. If you ask it for the next match it will give you the second quoted string.

网友答案:

If you want to find first quote's text without the ' you can/should use Lookahead and Lookbehind mechanism like

(?<=').*?(?=')

for example

System.out.println("hello 'cool1' word! 'cool2'".replaceFirst("(?<=').*?(?=')", "ABC"));
//out -> hello 'ABC' word! 'cool2'

more info

网友答案:

You could just split the string on quotes and get the second piece (which will be between the first and second quotes).

If you insist on regex, try this:

/^.*?'(.*?)'/

Make sure it's set to multiline, unless you know you'll never have newlines in your input. Then, get the subpattern from the result and that will be your string.

To support double quotes too:

/^.*?(['"])(.*?)\1/

Then get subpattern 2.

相关阅读:
Top