简体   繁体   English

检查正则表达式是在字符串的开头还是在特定字符之后开始

[英]Check if regex starts at the beginning of the string or after specific character

I have a regex pattern.我有一个正则表达式模式。 I want to check if it matches at the beginning of the string or after a new line or after a white space.我想检查它是否在字符串的开头、新行之后或空格之后匹配。

I also would like to make sure it matches the end of the string, after a new line or a white space.我还想确保它在换行或空格之后匹配字符串的结尾。

How do I make this condition "beginning or white space" ?我如何使这个条件“开始或空白”? Do I have to repeat myself我必须重复自己吗

Example:例子:

"Crazy Fredrick bought many very exquisite opal jewels" “疯狂的弗雷德里克买了很多非常精美的蛋白石珠宝”

The search for s should only match the last character "s" in "jewels".s的搜索应该只匹配“jewels”中的最后一个字符“s”。 The "s" in "exquisite" should not match. “精致”中的“s”不应该匹配。

This code is a regular expression starting with T and ending with s.Now if you want to check for each word in sentence split it by space and then use regular expression as per your requirement.此代码是一个以 T 开头并以 s 结尾的正则表达式。如果您想检查句子中的每个单词,请将其按空格分开,然后根据您的要求使用正则表达式。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression {
   public static void main(String[] args) {
   Pattern p = Pattern.compile("^(T).*[s]$");
   Matcher m = p.matcher("This is testingsd");
   System.out.println(m.matches());
   }
}

In JavaScript, you can use the character \\b , which according to MDN's RegExp page在 JavaScript 中,您可以使用字符\\b ,根据MDN 的 RegExp 页面

Matches a zero-width word boundary, such as between a letter and a space.匹配零宽度字边界,例如字母和空格之间。

So to match the s in the word "jewels" in your example, I would use the regex:因此,要在您的示例中匹配单词“jewels”中的 s,我将使用正则表达式:

var regex = /s\b/g;

To match every word that ends with "y", I can use要匹配以“y”结尾的每个单词,我可以使用

var regex = /\w*y\b/gi;

and it would produce the result "Crazy, very, many".它会产生结果“Crazy, very, many”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM