Home:ALL Converter>get character only string from another string in sql server

get character only string from another string in sql server

Ask Time:2014-10-22T19:01:19         Author:IrfanRaza

Json Formatter

I am looking for solution to get a character based string extracted from another string. I need only first 4 "characters only" from another string. The restriction here is that "another" string may contain spaces, special characters, numbers etc and may be less than 4 characters.

For example - I should get

  1. "NAGP" if source string is "Nagpur District"

  2. "ILLF" if source string is "Ill Fated"

  3. "RAJU" if source string is "RA123 *JU23"

  4. "MAC" if source string is "MAC"

Any help is greatly appreciated.

Thanks for sharing your time and wisdom.

Author:IrfanRaza,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/26505966/get-character-only-string-from-another-string-in-sql-server
vks :

^([a-zA-Z])[^a-zA-Z\\n]*([a-zA-Z])?[^a-zA-Z\\n]*([a-zA-Z])?[^a-zA-Z\\n]*([a-zA-Z])?\n\n\nYou can try this.Grab the captures or groups.See demo.\n\nhttp://regex101.com/r/rQ6mK9/42",
2014-10-22T11:12:16
Satyajit :

You can use the answer in the question and add substring method to get your value of desired length\nHow to strip all non-alphabetic characters from string in SQL Server?\n\ni.e.\n\nCreate Function [dbo].[RemoveNonAlphaCharacters](@Temp VarChar(1000))\nReturns VarChar(1000)\nAS\nBegin\n\n Declare @KeepValues as varchar(50)\n Set @KeepValues = '%[^a-z]%'\n While PatIndex(@KeepValues, @Temp) > 0\n Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')\n\n Return @Temp\nEnd\n\n\nuse it like\n\nSelect SUBSTRING(dbo.RemoveNonAlphaCharacters('abc1234def5678ghi90jkl'), 1, 4);\n\n\nHere SUBSTRING is used to get string of length 4 from the returned value.",
2014-10-22T11:20:51
yy