gpt4 book ai didi

Java正则表达式匹配模式

转载 作者:行者123 更新时间:2023-11-30 04:45:49 25 4
gpt4 key购买 nike

我需要根据某些文本检查模式(我必须检查我的模式是否在许多文本中)。

这是我的例子

String pattern = "^[a-zA-Z ]*toto win(\\W)*[a-zA-Z ]*$";    
if("toto win because of".matches(pattern))
System.out.println("we have a winner");
else
System.out.println("we DON'T have a winner");

对于我的测试,模式必须匹配,但使用我的正则表达式不匹配。必须匹配:

" toto win bla bla"

"toto win because of"
"toto win. bla bla"


"here. toto win. bla bla"
"here? toto win. bla bla"

"here %dfddfd . toto win. bla bla"

不得匹配:

" -toto win bla bla"
" pretoto win bla bla"

我尝试使用我的正则表达式来完成此操作,但它不起作用。

你能指出我做错了什么吗?

最佳答案

这可行

(?im)^[?.\s%a-z]*?\btoto win\b.+$

说明

"(?im)" +         // Match the remainder of the regex with the options: case insensitive (i); ^ and $ match at line breaks (m)
"^" + // Assert position at the beginning of a line (at beginning of the string or after a line break character)
"[?.\\s%a-z]" + // Match a single character present in the list below
// One of the characters “?.”
// A whitespace character (spaces, tabs, and line breaks)
// The character “%”
// A character in the range between “a” and “z”
"*?" + // Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
"\\b" + // Assert position at a word boundary
"toto\\ win" + // Match the characters “toto win” literally
"\\b" + // Assert position at a word boundary
"." + // Match any single character that is not a line break character
"+" + // Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"$" // Assert position at the end of a line (at the end of the string or before a line break character)

更新1

(?im)^[?~`'!@#$%^&*+.\s%a-z]*? toto win\b.*$

更新2

(?im)^[^-]*?\btoto win\b.*$

更新3

(?im)^.*?(?<!-)toto win\b.*$

说明

"(?im)" +       // Match the remainder of the regex with the options: case insensitive (i); ^ and $ match at line breaks (m)
"^" + // Assert position at the beginning of a line (at beginning of the string or after a line break character)
"." + // Match any single character that is not a line break character
"*?" + // Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
"(?<!" + // Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind)
"-" + // Match the character “-” literally
")" +
"toto\\ win" + // Match the characters “toto win” literally
"\\b" + // Assert position at a word boundary
"." + // Match any single character that is not a line break character
"*" + // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
"$" // Assert position at the end of a line (at the end of the string or before a line break character)
<小时/>

正则表达式需要转义才能在代码中使用

关于Java正则表达式匹配模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10993334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com