Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regular Expression Query

 
kayanaat sidiqui
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I need to search for string in the form of
1. name="<anything>"
2. name="<anything.anotherThing>"

I am using the following code--




It's giving output like--




Can you please point out where i m doing mistake?

Thanks,
Kaya.
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this RE:



I suppose '?' stands for 0 or 1 times
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's investigate your regex.

(name): the literal text name, grouped for some reason. So far so good.
=: the literal = symbol. So far so good.
- ([[\"]\\w.w[\"]]+): a group you want to use to capture the value. Let's dissect that:

[[\"]\\w.w[\"]]+: you have two character classes ([\"]) inside another character class. This will create a union of the character classes. In other words, this regex is saying: one or more characters from the character class that contains a double quote, a word character, a dot, a literal w and (again) a double quote. In other words, it doesn't stop at a double quote if another dot word character follows.


Let's re-create your regex.

- part 1: the literal "name": name
- part 2: the literal "=": =
- part 3: your group:
-- part 3.1: start with a quote: "
-- part 3.2: anything: \w+
-- part 3.3: a dot followed by anotherThing: \.\w+. However, it is optional, so it becomes (\.\w+)?
-- part 3.4: end in a quote: "

Put that together, and you get name=("\w+(\.\w+)?")
Put that into a Java string (so escape the " and \ characters with another \) and you're done. Note however that you'll now need to use group(1); group(2) is now the optional .anotherThing part. You can help your regex engine a bit by telling it to ignore the last group by putting a ?: right after the parenthesis: name=("\w+(?:\.\w+)?")
This way, group(0) will be the entire matched string, group(1) will be the thing you want and group(2) and up do not even exist.
 
kayanaat sidiqui
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Rob for the descriptive solution.
It was really very helping content you wrote.
Can you please share the link to read more about regular expressions.

Thank you Sagar for your quick response.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.util.regex.Pattern has a lot of information on regular expressions in Java.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic