2

I need to implement pattern matching using sqlserver...

These are the following conditions-

  1. The first letter of the word should start with a character. 2.It can be upper or lower case 3.The following characters after the 1st chacter can by numbers 1-9 or any valid characters or underscore..

Basically I need to implement this regular expression logic in sqlserver

'/^[a-zA-Z][a-zA-Z0-9_]*$/

I'm sure this will work

ie;

select var_1 from table_1 where var_1 like [a-z] but not sure how if all the logic can be implemented

4

2 Answers 2

4

For the RegEx /^[a-zA-Z][a-zA-Z0-9_].*$/:

WHERE somecolumn LIKE '[a-Z][a-Z0-9_]%'  -- column
WHERE @somecolumn LIKE '[a-Z][a-Z0-9_]%' -- variable

i.e.

select var_1 from table_1 where var_1 like '[a-Z][a-Z0-9_]%'

FYI Unless you have changed the defaults, most SQL Server databases are not collated to be case sensitive. Therefore, the LIKE range [a-z] will include all letters, upper or lower case. The singular character % matches ZERO to ANY number of characters.

The start of the string (^ in RegExp) is implicit by the fact that the LIKE pattern is not prefixed by %.

Reference: LIKE (Transact-SQL)


For the RegEx /^[a-zA-Z][a-zA-Z0-9_]*$/:

Use the pattern in T I's comment, i.e.

WHERE var_1 LIKE '[a-Z]%' AND NOT var_1 LIKE '%[^a-Z0-9_]%'

The first part ensures that the first character is a letter; the second part ensures that in any position (including first), the only valid characters are alphanumerics or underscore, by exclusion (^).

Sign up to request clarification or add additional context in comments.

3 Comments

How does the '*' will be handled??
Can you explain more on ^ character..In python ^ means "matches the beginning line of string for ex:^He will be True for "Hello" "
^ is required in regular RegEx because the matches are implicitly "anywhere" so ^ anchors the start of the match to the beginning of string. In SQL Server, matches start at the beginning of string unless there is a '%' to make it match anywhere.
0
select * ,UPPER(LEFT(DesEng, 1)) +LOWER(RIGHT(DesEng, LEN(DesEng) - 1)) as b from C_Communes where LEN(DesEng) >1

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.