Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: regex - how do i get the first quote text

Tags:

java

regex

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.. )

like image 575
Popokoko Avatar asked May 26 '12 21:05

Popokoko


2 Answers

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

like image 21
Pshemo Avatar answered Sep 28 '22 19:09

Pshemo


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.

like image 198
Mark Byers Avatar answered Sep 28 '22 19:09

Mark Byers