hoju
hoju

Reputation: 29452

regular expression that ignores case of first character

I know JavaScript regular expressions can ignore case for the entire match, but what about just the first character? Then hello World! would match Hello World! but not hello world!.

Upvotes: 0

Views: 3853

Answers (5)

davr
davr

Reputation: 19137

Do it another way. Force the first character of your data string to lower case before matching it against your regular expression. Here's how you'd do it in ActionScript, JavaScript should be similar:

var input="Hello World!";
var regex=/hello World!/;
var input2 = input.substr(0, 1).toLowerCase() + input.substr(1);
trace(input2.match(regex));

Upvotes: 2

polygenelubricants
polygenelubricants

Reputation: 383726

regular-expressions.info

  • Character Classes or Character Sets

    With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an a or an e, use [ae]. You could use this in gr[ae]y to match either gray or grey.


Thus, a regex that matches Tuesday and tuesday, and nothing else, is [Tt]uesday.


If you're given an arbitrary word w, and a subject s that needs to match w, except that the first letter is case-insensitive, then you don't really need regular expressions. Just check that the first letter of w and s is the same letter, ignoring case, then make sure that the substring of w and s from index 1 matches exactly.

In Java, it'd look something like this:

boolean equalsFirstLetterIgnoreCase(String s, String w) {
   return s.substring(0, 1).toLowerCase().equals(w.substring(0, 1).toLowerCase())
     && s.substring(1).equals(w.substring(1));
}

Upvotes: 1

Zarigani
Zarigani

Reputation: 835

Your question doesn't really make sense. Since the edit, it now says "I am after a general regular expression that can be applied to all words.". The regex to match all words and punctuation would be ".*"

What are you trying to match? Can you give examples of what should match and what should not match?

Upvotes: 2

Ben
Ben

Reputation: 16543

[a-zA-Z]{1}[a-z]

Upvotes: 2

Eli
Eli

Reputation: 5610

You mean like /[Tt]uesday/

The [Tt] creates a set, which means either 'T' or 't' can match that first character.

Upvotes: 6

Related Questions