I am new to regex expressions so sorry if this is a really noob question.
如果这是一个真正的问题,我对regex表达式很抱歉。
I have a regex expression... What I want to do is check if a string matches the regex expression in its entirety without the regex expression matching any subsets of the string.
我有一个regex表达式…我要做的是检查一个字符串是否完全匹配regex表达式,而没有regex表达式匹配字符串的任何子集。
For example...
例如……
If my regex expression is looking for a match of \sA\s*, it should return a match if the string it is comparing it to is " A " but if it compares to the string " A B" it should not return a match.
如果我的regex表达式正在寻找与之匹配的\sA\s*,那么如果它正在比较的字符串是“a”,那么它应该返回一个匹配,但是如果它与字符串“a B”比较,那么它不应该返回一个匹配。
Any help would be appreciated? I code in C#.
有什么需要帮忙的吗?我在c#代码。
1 个解决方案
#1
16
You would normally use the start end end anchors ^
and $
respecitvely:
您通常使用开始结束结束锚^和$ respecitvely:
^\s*A*\s*$
Keep in mind that, if you regex engine supports multi-line, this may also capture strings that span multiple lines as long as one of those lines matches the regex(since ^
then anchors after any newline or string-start and $
before any newline or string end). If you're only running the regex against a single line, that won't be a problem.
记住,如果你正则引擎支持多行,这个也可以捕捉字符串跨越多个行,只要其中一个线匹配的正则表达式(因为^后锚任何换行符或string-start美元任何换行符之前或字符串)。如果你只在单行上运行regex,那就不会有问题。
If you want to ensure that a multi-line input is only a single line consisting of your pattern, you can use \A
and \Z
if supported - these mean start and end of string regardless of newlines.
如果您想要确保多行输入仅是由您的模式组成的一行,您可以使用\ a和\Z(如果支持的话)—这些意味着字符串的开始和结束,而不考虑换行。
#1
16
You would normally use the start end end anchors ^
and $
respecitvely:
您通常使用开始结束结束锚^和$ respecitvely:
^\s*A*\s*$
Keep in mind that, if you regex engine supports multi-line, this may also capture strings that span multiple lines as long as one of those lines matches the regex(since ^
then anchors after any newline or string-start and $
before any newline or string end). If you're only running the regex against a single line, that won't be a problem.
记住,如果你正则引擎支持多行,这个也可以捕捉字符串跨越多个行,只要其中一个线匹配的正则表达式(因为^后锚任何换行符或string-start美元任何换行符之前或字符串)。如果你只在单行上运行regex,那就不会有问题。
If you want to ensure that a multi-line input is only a single line consisting of your pattern, you can use \A
and \Z
if supported - these mean start and end of string regardless of newlines.
如果您想要确保多行输入仅是由您的模式组成的一行,您可以使用\ a和\Z(如果支持的话)—这些意味着字符串的开始和结束,而不考虑换行。