BigBug
BigBug

Reputation: 6290

Regex - parsing string

Say i have a file which contains lines as follows:

Hayden
y

Suppose i want to manipulate the line which only contains "y" and not the one with Hayden, how would i do this?

So i read in the file and parse it line by line. I want to say if the line contains letters before or after "y" then it's not the line i'm looking for.

I thought i could do the following:

String value = "y"; 
if(strLine.matches("[a-zA-Z]" + value + "[a-zA-Z]"))
{
      don't manipulate line here
}
else
{
   manipulate string here
}

However, this gets "Hayden" as well as "y"

Any ideas?

EDIT

sorry, i should have been more clear, what if i don't mind if there are spaces or symbols in front? or behind? it's specifically the letters that i need to watch out for. For instance, i can't have yh but i can have y=... sorry again

Upvotes: 1

Views: 111

Answers (5)

Pshemo
Pshemo

Reputation: 124215

Maybe this is what you are looking for

String[] lines={"Hayden","y"," y*","y=","y+"," +y..."};
for (String s:lines)
    System.out.println(s+"->"+s.matches("\\W*y\\W*"));

output:

Hayden->false
y->true
 y*->true
y=->true
y+->true
 +y...->true

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 837916

You can use negative lookarounds:

if (strLine.matches("^.*(?<![a-zA-Z])y(?![a-zA-Z]).*$")) { 
    // manipulate string here
}

The anchors are optional but included anyway for clarity.

Upvotes: 4

Reimeus
Reimeus

Reputation: 159754

You can use:

strLine.matches("^y$")

To ignore symbols, i.e. non-alphanumeric characters, use:

strLine.matches("^\\W*y\\W*$")

Upvotes: 3

Bergi
Bergi

Reputation: 664185

Extending the equals approach: Just remove all the character you don't mind, and then check for equality with "y":

if (strLine.replaceAll("[^a-zA-Z]", "").equals("y")) {
    ...
}

Upvotes: 0

Blender
Blender

Reputation: 298046

If you are going to use regex, you need to be a bit more specific:

  • y matches a y anywhere in the line.
  • ^y$ matches a y that is right before the end of the string (the dollar sign) and right after the beginning of the string (the caret). This lets you match the line that is equal to y.

Upvotes: 0

Related Questions