Regex: must start with a letter or a number but the rest can be anything

谁说我不能喝 提交于 2021-02-05 07:01:07

问题


I am trying to construct a pattern in order to use in validation.

My goal is to have the first character to be a letter or a number, the rest anyhing.

i.ex:

  1. A'r4nd0m!
  2. 9!h3ll0.
  3. b1llin6s

I thought of: [a-zA-Z0-9_/][.*]++

What would be the solution?

Thank you!


回答1:


As I’ve commented, a letter or a number is [\pL\pN]. Therefore a string beginning with one of those would match the pattern

/^[\pL\pN]/



回答2:


If the first number is a number or letter, you have ^[A-Za-z0-9]. (The ^ matches the beginning of the string.) For the rest to be anything, a simple .* will suffice, so you have ^[A-Za-z0-9].*.




回答3:


You can trim down your regex a little:

^[a-zA-Z0-9].*

Starts with letter/number, can be of any length or any characters after.




回答4:


You must anchor your regex at the start of the string, using /^/. Your character class [a-zA-Z0-9_/] also matches an underscore and a slash: is this what you intend? Also, [.*]++ matches one or more dots or stars, and the trailing + superfluously duplicates the quantifier.

Since the remainder of the string can be "anything" there is no point in matching it, and

/^[A-Za-z0-9]/

will do fine.



来源:https://stackoverflow.com/questions/9295589/regex-must-start-with-a-letter-or-a-number-but-the-rest-can-be-anything

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!