mad hatter
mad hatter

Reputation: 35

regex help on searching a string for a match

What I need to do is check a string and this is what I have so far

System.out.print("Please enter a string of 1's and 0s :");
numLine = input.next();

if (numLine.matches("^101$")) {
    System.out.print("A is true");
} else if (numLine.matches("^\\d[01]+101$ ")){
    System.out.print("B is true");
} else {
    System.out.println("no");  
}

The first part of the code the ^101$ works and prints out A is true for B what I am trying to do is only accept 1s and 0s and return if it ends in 101 and I would like a C to do 101 at the begining and accept as many 1s and 0s and a D that does 101 anywhere in it even if its 111000101000 or something else

the killer for me is the ("^101$") syntax and I could use help with that

Upvotes: 1

Views: 45

Answers (3)

arshajii
arshajii

Reputation: 129567

You don't need ^ and $ with matches (as I said in my comment). Here's the way I see it:

B: "[01]+101"
C: "101[01]+"
D: "[01]*101[01]*"


Recall that X+ means X one or more times and that X* means X zero or more times.

Also (for A), if you want to 'match' only "101", you might want to consider simply using equals instead, i.e. numLine.equals("101").

Upvotes: 2

MartinHaTh
MartinHaTh

Reputation: 1447

I'm not sure exactly what you wanted to do, but I understood what you wanted regex for, so I'll simply post that.

A - ^101$ matches 101 as the whole string.

B - ^101 matches 101 at the beginning of a string. Add [10]* after, to include 0 and 1 after. ^101[10]*

C - 101$ matches 101 at the end of a string. Add [10]*^ at the beginning to include preceding 0 and 1. [10]*101$

D - 101 matches 101 anywhere.

Upvotes: 0

murgatroid99
murgatroid99

Reputation: 20297

The four regular expressions you want are very similar:

To match exactly "101" (A), as you found, use 101 (as mentioned in the comments, you don't need to use ^ and $.

To match anything that ends with "101" (B), use [01]*101.

To match anything that begins with "101" (C), use 101[01]*.

To match anything that contains "101" (D), use [01]*101[01]*.

In all cases, [01]* means 0 or more instances of any character in the set {0,1}, so each of these looks for 101 with the rest of the string filled out as applicable with only 0 and 1.

Upvotes: 1

Related Questions