• Post Reply Bookmark Topic Watch Topic
  • New Topic

Unable to match a regex  RSS feed

 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to create a fairly simple regex to match some text and am having a difficult time with it. In this case, there's a single form field in which the user may enter a name or they may enter both a name and phone number. If it's the latter, I need to break the two pieces apart to persist them properly.

So, for example, the following bits of text would all be considered "valid" inputs:



So I'd like to write a little bit of code that would identify the middle two cases and tear them apart. I'm running under the assumption that no name will actually have a number in it so any numbers that appear will be a phone number. Also, the phone number will allways be entered last and with one space between the name and the phone number.

Here's what I originally created:



Unfortunately, that never matches anything, even if I'm using an input that I think it should match. So to test if my regex was working, I changed it to just this:



For my input, I used "johnson 23412". This also fails to match.

What do I have screwed up here that my regexes don't seem to match anything, at all?

Thanks,
Corey
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The dreaded double escape.




output:

Of course, this is eating your "1", but that's the next problem to solve.

From the regex documentation, backslash section, Pattern class: "The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary."
[ January 19, 2008: Message edited by: Bill Shirley ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One problem is that matches() only returns true if the entire input matches the expression. So "johnson 23412" dies not match "john", but it would jatch "john.*".

Also, most of your earlier regexes are matching a single letter, or single number. To match input with at least one number, try this:

To cover all three cases at once, I might try something like this:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!